synchronized
1, the characteristics of the lock mechanism
- Mutual exclusivity: at the same time allows a thread holding an object lock (atomicity) only
- Visibility: You must ensure that before the lock is released, to modify the shared variable is located, and then get another thread for the lock is visible
2, synchronized use
2.1 Classification lock
- Object lock: synchronized (this | object) modification of non-static methods
Each object will have a monitor object that is locked java object
object class can have more, so each object has its own independent object lock, and do not interference Locks: synchronized (class .class) modified static methods
class object lock by lock is actually implemented, class lock that is the object class
Each class has only one Class object, so each class has only one class lock2.2 lock principle (monitor)
- With the use of code blocks is achieved by a locking and monitorExist monitorenter
By locking method is expressed as ACC_SYNCHRONIZED achieve
2.3 java virtual machine optimization of synchronized
An object instance comprising: object header, instance variables, stuffing data
object header contains information lock flag bit:
- When the other thread contention fails, do not immediately convert the level of the lock, but the implementation of air circulation (spin locks)
- Lock exclude: JIT at compile time to remove unnecessary lock