Introduction to the
The synchronized keyword is a way of addressing resource synchronization in Java by ensuring that a code block or method it modifies can only be accessed by one thread at any time.
The low-level implementation of synchronized keyword
We do this by writing a piece of code and decompiling its bytecode file
public class SynchronizedDemo3 {
public void method(a) {
synchronized (this) {
System.out.println("SynchronizedDemo3"); }}}Copy the code
As you can see from the bytecode files, the bottom layer is implemented through the Monitorenter and Monitorexit directives.
Each object has a monitor lock. A contention for resources is really a contention for the monitor. When a thread attempts to acquire ownership of the monitor through the Monitorenter, if the number of monitor entries is zero, The thread enters the Monitor and sets the number of entries to 1. At this point, the thread takes ownership of the Monitor. If the thread accesses the monitor again, the number of entries is continued +1. When another thread attempts to acquire the ownership of monitor and finds that the number of monitor entries is greater than 0, it is occupied by another thread and will be blocked. By executing monitorexit, the thread that owns monitor will change the number of monitor entries to -1. When the number of monitor entries decreases to 0, This indicates that the thread is no longer the owner of monitor, and it will wake up the blocked thread to try to acquire monitor.
We can see that two MonitoreXit appear in the bytecode file above, the first for normal exit lock and the second for exception exit lock.
Why is synchronized a heavyweight lock? Because the monitor lock the underlying operating system involved the mutex, Java thread is in the final analysis is mapped to the operating system thread above, at this time when we went to the blocked, or if you wake up one thread needs to be operating system user mode and kernel mode of a switch, the process is very time consuming and resource.
The difference between synchronized and lock
- Lock is an interface, synchronized is a built-in Java keyword;
- Lock causes a deadlock (in finally) when an exception occurs, whereas synchronized does not.
- Lock manually releases the lock, while synchronized automatically releases the lock.
- Lock can tell if a lock has been successfully acquired, whereas synchronized cannot.
- Lock improves read operations (read/write locks) for multiple threads.
The difference between synchronized and volatile
- Volatile emphasizes the visibility of variables across multiple threads; Synchronized emphasizes a synchronization of access to resources by a thread;
- Volatile modifies variables, while synchronized modifies methods and code blocks;
- Multiple threads accessing volatile do not block, whereas synchronized does;
- Volatile does not guarantee atomicity, whereas synchronized does.