What makes immutable objects to be published without safe publication techniques?

匿名 (未验证) 提交于 2019-12-03 00:56:02

问题:

What does it mean to say that immutable objects can be published even without resorting to safe publication idioms?

I have read Java Concurrency in Practice (Chapter 3 , Sharing Objects) but still not able to comprehend the statement :

Immutable objects can be published through any mechanism.

               V/S  

Effectively immutable objects should be safely published.

Edit: I have been through a similar question on SO and the answers but still unable to understand how immutable objects can be published safely because there is a chance that the field referencing the immutable object will be seen as null or some stale value from earler invocations by an external thread.

回答1:

Not every use case needs to see a new instance at any precise moment. Consider the textbook example: lazily-initialized singletons which are cheaper to re-initialize in each thread than to share safely. In such a case you may unsafely share an immutable instance and each thread which doesn't manage to receive the already existent copy will just create its own.

As for terminology: unsafe publication means that it happens under a data race. Safe publication is the opposite case.

BTW java.lang.String is an example of an effectively immutable object which can nevertheless be shared unsafely.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!