Before chatting, let’s talk about the three features of concurrent programming.
Concurrent programming features
- Atomicity: A set of operations on shared resources will either succeed or fail, and there will be no partial success or partial failure.
- Visibility: When a thread acquires triviality, it will copy a shared resource to local memory, and when the lock is released, the shared resource will be refreshed to the main memory. Visibility means that when a shared resource changes, other threads can see this change.
- Orderability: In order to improve efficiency, the compiler and processor will reorder the code instructed. In the case of single thread, the instruction replay will not be affected, and in the case of multi-threading, the correctness of code execution may be affected. Order means that the order of code writing and execution are consistent.
volatile
volatileIt is the lightest synchronization mechanism provided by the JVM, and the compiler will not optimize it.
characteristic:
- volatileOnly guaranteed to share resourcesVisibilityandOrderful。
- usevolatileWhen modifying shared resources, if the shared resources change, the cached data will be directly written back to the main memory, and the data will also be read from the main memory, thus ensuring visibility.
- volatileThe underlying layer is implemented through the operating system's memory barrier. Since the memory barrier is used, instruction re-ordering will be prohibited, thus ensuring order.
Where it works:
volatileOnly used to modify member variables.
public class VolatileTest { private volatile static String staticVolatile; private volatile String memberVolatile; }
synchronized
synchronizedThe keyword is a built-in lock provided by Java to ensure that we synchronize shared resources. It will automatically lock and release the lock. Its lock is a non-fair lock.synchronizedThe keyword markings will be optimized by the compiler.synchronizedThis will cause threads to execute serially, which may cause thread blockage.
characteristic
- synchronizedKeywords enable threads to be executed serially, so they ensure three concurrency security, and also have the following two features:
- Mutual Exclusion: At the same time, only one thread can access the synchronized method or synchronized code block.
- Reentrability:synchronizedIt is a reentrant lock. In common explanation, a reentrant lock means that when a thread acquires an object lock or class lock, the thread calls other synchronized methods or code blocks of the lock before releasing the lock, it does not need to reacquire the lock again.
Where it works
synchronizedKeywords can be used to modify methods or code blocks.
Modification methods, divided into example methods and static methods
- Modify instance method, object lock
public synchronized void objectMethods(){ ..... }
- Modify static methods, class lock
public static synchronized void staticMethods(){ ..... }
Modify code blocks
Obj is a reference to an object Object lock
public void objectMethods(){ synchronized (obj){ } }
Object is a class lock
public void classLock(){ synchronized (){ } }
ReentrantLock
LockIt is an interface with a lock mechanism provided by Java 5.ReentrantLockyesLockAn implementation of the internal implementation is throughAQS(AbstractQueuedSynchronizer)Achieved.ReentrantLockTranslated as reentrant lock, it andsynchronizedsimilar,ReentrantLockNeed to manually add and release the lock, relative tosynchronizedIt is more flexible and provides more methods.ReentrantLockThere are two ways to use fair lock and unfair lock, and the default is to use fair lock.
characteristic
ReentrantLockIt is a reentrant synchronization lock, so it has three major features of concurrent programming, but also reentrant.
Where it works
ReentrantLockis a class that can be used as a member variable or as a local variable. When used as a member variable and a local variable, the methods used are a little different. No matter which method is used, don't forget to call it in the end.unlock()
Method to manually release the lock.
Use format as member variables:
private Lock globalLock = new ReentrantLock(); public void globalLock(){ if (()) { try { } catch (Exception e) { }finally { (); } } }
The abovetryLock()
The method is to try to acquire the lock. If the acquisition is successful, return true, otherwise it will return false, and it can also be replaced with a waiting time added.boolean tryLock(long time, TimeUnit unit)
Method: If the lock is successfully acquired within the set waiting time, it will return true, otherwise false.
Use format as local variables:
public void lock(){ Lock lock = new ReentrantLock(); (); try { }finally { (); } }
contrast
A brief comparison of the differences between the three:
volatile | synchronized | ReentrantLock | |
Is it a keyword? | yes | yes | no |
Do you need to manually add/release locks? | no | no | yes |
Can concurrency security be guaranteed | no | yes | yes |
Is it a fair lock? | \ | no | There are two implementations: fair lock and unfair lock |
Will block threads | no | yes | yes |
Will the JVM optimize it | no | yes | no |
characteristic | Visibility, orderliness | Visibility, orderliness, atomicity | Visibility, orderliness, atomicity |
Place to use | Member variables | Methods, code blocks | Member variables, local variables |
This is the end of this article about the differences and comparisons of synchronized, volatile, and ReentrantLock. For more information about synchronized, volatile, and ReentrantLock, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!