Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top