Multithreading the synchronized keyword

Java synchronized to a mutex lock is heavyweight, after adding synchronized method will bring the cost of performance, so do the balance between performance and security.

synchronized lock range

  1. Member method:
    public void the synchronized Demo () - are members of the method, the object lock is set, that is, two threads access the same instance of an object, it will produce mutually exclusive.
//等同
public void demo(){
	synchronized(this){
	
	}
}
  1. Static method:
    public static void the synchronized Demo () - method belongs to the class, the class lock is set, that is, when two threads simultaneously access a class, will produce mutually exclusive.
//等同
public static demo(){
	synchronized(Demo.class){
	}
}

Knowledge summary

  1. in synchronized lock object header identifies
  2. Monitors monitorenter enter -> lock; withdraw the monitorexit Monitor -> release lock
  3. jdk1.6 added to the biased locking lock and lightweight
  4. Biased locking is to solve the problem is: most of the time do not need to lock a thread or a multiple lock acquired by a thread, in order to reduce the cost of acquiring the lock, the lock is provided biased, and therefore do not tend to lock is released, the next time the thread continues time of the visit no longer need to obtain the favor, and more like a junior pass.
  5. Lightweight lock problem is: a small number of threads competing for the same resources and their operating time is short, there is no need to thread blocking (blocking because the cost is relatively large), there is no competition to the thread will lock a fixed number of polling to get the lightweight lock.
  6. CPU thread blocks need to transition from user mode to kernel mode, the cost is relatively large.
  7. synchronized automatically releases the lock when an exception is encountered, and synchronized can not be interrupted.
  8. synchronized belong pessimistic locking
Published 56 original articles · won praise 3 · Views 1171

Guess you like

Origin blog.csdn.net/qq_40788718/article/details/103681300