synchronized and Lock difference

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/longgeqiaojie304/article/details/91354243

synchronized and Lock difference

Manufacturers face questions:

We all know that ArrayList is not thread-safe, please write coding unsafe and gives the case a solution?

Lock fair / unfair lock / reentrant lock / recursive lock / spin locks talk about your understanding? Please handwriting a spin lock.

CountDownLatch, CyclicBarrier, Semaphore used it?

Blocking queue know?

Thread pool used it? ThreadPoolExecutor talk about your understanding?

Thread pool used it? Production How do you set reasonable parameters?

Deadlock coding and positioning analysis?

1, synchronized and Lock difference

(1) original configuration

       sychronized is a key part of JVM level,

       monitorenter, monitorexit (underlying object is accomplished by a monitor, in fact, wait / notify method is also dependent on the monitor object, or only in the sync block synchronization process can call wait / notify or the like);

 

       Lock belongs to a specific class (java.util.concurrent.locks.lock) is api-level locks.

 

(2) use

       synchronized without requiring the user to manually release the lock, when the synchronized code execution is complete, the system will automatically make the thread releases the lock on the occupation;

       ReentrantLock the user is required to manually release the lock, if not take the initiative to release the lock, it may lead to a deadlock. We need to lock (), unlock () method with the try / finally statement block to complete.

 

If (3) wait for interruptible

       synchronized not be interrupted, unless an exception is thrown or normal operation completed;

       ReentrantLock interruptible:

  1. The method of setting the timeout tryLock (long timeout, TimeUnit unit)
  2. lockInterruptibly in () to put the code block, the call interrupt () method interruptible

 

(4) lock whether fair

       synchronized unfair lock

       Both can ReentrantLock, the default non-fair lock configuration method can be passed a boolean, value of true indicates fair passed lock, incoming false value means unfair lock.

 

(5) a plurality of lock binding conditions Condition

       synchronized multiple conditions can not be bound

       ReentrantLock used to implement packet needs to wake up the thread who can wake precise, synchronized rather than as just wake up one thread or all threads.

Guess you like

Origin blog.csdn.net/longgeqiaojie304/article/details/91354243