Explain the use of "mutability" in java?

I am learning about the "volatile" keyword in Java. But I don't know how to use it correctly. And I found some uses in the JDK. Can you explain to me why using volatile?

1) class HashMap

: transient volatile int modCount;


I think this is because of the visibility, once the map is changed by another thread, other threads can see the change. right?

2) Inner static class HashEntry

in ConcurrentHashMap


final K key;
final int hash;
volatile V value;


Why a value using volatile?

3) class AtomicInteger

: private volatile int value;


4) class ThreadPoolExecutor


private volatile long  keepAliveTime;
private volatile int   corePoolSize;
private volatile int   maximumPoolSize;


Is it all because of visibility? Or some other deeper reasons?


source to share

2 answers

Volatile is used when you want to make something modifiable across multiple threads. It marks a variable that cannot be cached locally for any thread. All reads and writes are kept in memory for all of your threads.



The volatile keyword in Java is used as an indicator for the Java compiler and Thread, which do not cache the value of this variable and always read it from main memory.

More details: http://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.html#ixzz3FER8Hvj8



All Articles