multithreading - Unsafe publication concurrency java -


this question has answer here:

java concurrency in practice book has given example unsafe publication

public class holder  {     private int n;     public holder(int n)     {         this.n = n;      }     public void assertsanity()      {         if (n != n)             throw new assertionerror("this statement false.");     } } 

the above code seems thread safe. not thread safe if n public variable. book example wrong?

safe publication memory visibility. concept of memory visibility bit trickier other thread safety issues such race conditions.

memory visibility issues arise when actions performed 1 thread in order appear performed in different order thread (it may caused optimizations made compiler or cpu).

in case:

// thread h = new holder(42);  // thread b h.assertsanity(); 

for thread a, n initialized before h.

but in absense of safe publication it's not guaranteed same thread b. thread b may see h in initialized state, n won't initialzed yet. moreover, state of n observed thread b may change during evaluation of n != n, causing assertsanity() throw exception.

note problem not guaranteed happen in cases. never see happening, java memory model doesn't guarantee correctness in case nonetheless.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -