1. multi-thread --volatile

1. If a variable is declared with the volatile keyword then it is guaranteed that any thread that reads the field will see the most recently written value. The volatile keyword will not perform any mutual exclusive lock on the variable.

2. The simplest way to avoid problems with concurrency is to share only immutable data between threads.

To make a class immutable make:
1),all its fields final
2),the class declared as final
3),the this reference is not allowed to escape during construction


3. when to use volatile ?
1) if you want to read and write long and double variable atomically. long and double both are 64 bit data type and by default writing of long and double is not atomic and platform dependence.

2) Volatile variable can be used as an alternative way of achieving synchronization in Java in some cases, like Visibility. with volatile variable its guaranteed that all reader thread will see updated value of volatile variable once write operation  completed, without volatile keyword different reader thread may see different values.

3) volatile variable can be used to inform compiler that a particular field is subject to be accessed by multiple threads, which will prevent compiler from doing any reordering or any kind of optimization which is not desirable in multi-threaded environment.


你可能感兴趣的:(volatile)