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
- The method says static synchronized
- There is only one lock for the entire Object.class, and only one lock for all objects
object lock
- Only write synchronized in the method declaration
- 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
- The volatile keyword provides a lock-free mechanism for accessing domain variables,
- Using volatile to decorate a field is equivalent to telling the virtual machine that the field may be updated by other threads,
- So every time the field is used it is recalculated instead of using the value in the register
- 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
- ReentrantLock() : Create a ReentrantLock instance
- lock() : acquire the lock
- 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()