e.g. I have static field in multithreading enviroment (many threads use this variable):
public static int value;
Should I add volatile
to declaration to establish a happens-before relationship?
e.g. I have static field in multithreading enviroment (many threads use this variable):
public static int value;
Should I add volatile
to declaration to establish a happens-before relationship?
Instance association is orthogonal to concurrent modification.
if you access a static values through multiple thread each thread can have it's local cached copy To avoid this you can declare the variable as static volatile and this will force the thread to read each time the global value
Yes, that would be one way of doing it. Another way would be to access it using synchronized methods only.
Volatile fields are special fields which are used for communicating state between threads. Each read of a volatile will see the last write to that volatile by any thread; in effect, they are designated by the programmer as fields for which it is never acceptable to see a "stale" value as a result of caching or reordering. The compiler and runtime are prohibited from allocating them in registers. They must also ensure that after they are written, they are flushed out of the cache to main memory, so they can immediately become visible to other threads. Similarly, before a volatile field is read, the cache must be invalidated so that the value in main memory, not the local processor cache, is the one seen. There are also additional restrictions on reordering accesses to volatile variables.
http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#volatile
Note that if you also want atomicity in addition to the happens-before relationship, read the answer to this question : Java: Is there a right way to use static volatile variables?