Locks, distributed locks, lock-free distributed lock-free

Locks, distributed locks, lock-free distributed lock-free

 

 

Why have locks?

 

      To ensure resource thread safety, simply put, it will not be chaotic in the case of multi-threading.

 

 

 

Classification of locks

 

  • JVM locks: class locks, object locks, bias, fairness, reentrancy, deadlock
  • Distributed locks: Redis, DB, zookeeper

 

 

The difference between class lock and object lock

 

class lock

 

  1. The method says static  synchronized
  2. There is only one lock for the entire Object.class, and only one lock for all objects

 

object lock

 

  1. Only write synchronized in the method declaration
  2. Object's instantiated objects object1, object2, and object3 each have their own lock

 

 

 

How JVM locks are implemented

 

Synchronized method

 

public synchronized void save(){}

 

Note: The synchronized keyword can also modify static methods. If the static method is called at this time, the entire class will be locked.

 

 

 

sync block

 

synchronized(object){ 

}

     

Note: Synchronization is an expensive operation, so it should be minimized. 

 

 

 

volatile

 

  1. The volatile keyword provides a lock-free mechanism for accessing domain variables, 
  2. Using volatile to decorate a field is equivalent to telling the virtual machine that the field may be updated by other threads, 
  3. So every time the field is used it is recalculated instead of using the value in the register 
  4. volatile does not provide any atomic operations, nor can it be used to modify variables of final type 

Note: Although this can achieve thread safety, it has no atomicity, such as (i++)

 

 

 

Reentrant lock: ReenreantLock

 

  1. ReentrantLock() : Create a ReentrantLock instance 
  2. lock() : acquire the lock 
  3. unlock() : release the lock 

Note: ReentrantLock() also has a construction method that can create a fair lock, but it is not recommended because it can greatly reduce the efficiency of the program

 

 

 

Concurrent collection, concurrent tool class

 

  • ConcurrentHashMap
  • CopyOnWriteArrayList
  • Concurrency tool class: java.util.concurrent (JUC)

 

 

Atomic Operations: Atomic

 

 

Thread synchronization using local variables: ThreadLocal

 

 

 

Distributed lock

 

Redis

 

  • Single thread, fast, single point
  • 加锁:setNx()、取锁:getNx()
  • 或者setString也可以实现分布式锁

 

DB

 

悲观锁:select * from table for update(Quartz)

乐观锁:加多个version字段

 

 

Zookeeper:待学习。。。。。

 

 

 

无锁、分布式无锁

 

同样是使用redis实现,用它的自增功能,jedis.incr()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326205421&siteId=291194637