Various locks in java

Pessimistic lock: pessimistic lock pessimistically believes that every operation will cause the loss of updates, and an exclusive lock is added every time.

Every time I go to get the data, I think others will modify it, so every time I get the data, I will lock it. In this way, if others want to get the data, they will block it until it gets the lock. Many of these locking mechanisms are used in traditional relational databases, such as row lock, table lock, read lock and write lock, which are locked before operation.

Select * from xxx for update; (this for update is locking. Only one connection can operate the data, and all others are blocked)

Optimistic lock: always assume the best situation. Every time you get the data, you think others will not modify it, so you won't lock it. However, when updating, you will judge whether others have updated the data during this period. You can use the version number mechanism and CAS algorithm. Optimistic locking is applicable to multi read applications, which can improve throughput. For example, it is similar to write provided by the database_ The condition mechanism is actually an optimistic lock provided. In Java, Java util. concurrent. The atomic variable class under the atomic package is implemented by CAS, an implementation of optimistic locking.

From the above introduction to the two locks, we know that the two locks have their own advantages and disadvantages, and one cannot be considered better than the other. For example, optimistic locks are applicable to the case of less writing (multi read scenario), that is, when conflicts really rarely occur, which can save the cost of locks and increase the overall throughput of the system. However, in the case of multiple writes, conflicts will often occur, which will lead to the continuous retry of the upper application, which will reduce the performance. Therefore, it is more appropriate to use pessimistic lock in the general scenario of multiple writes.

Read write lock

comparison Locks in Java In the implementation of Lock, read-write Lock is more complex. Suppose your program involves read and write operations on some shared resources, and the write operations are not as frequent as the read operations. When there is no write operation, there is no problem for two threads to read a resource at the same time, so multiple threads should be allowed to read shared resources at the same time. However, if a thread wants to write these shared resources, no other thread should read or write to the resource. This requires a read / write Lock to solve this problem. Java 5 in Java util. The concurrent package already contains read-write locks. Nevertheless, we should understand the principle behind its implementation.

package com.zl.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

 * @author zhanglei
 * @description : java Read write lock in
 * @date 2021/4/8$ 15:32$
 * @return $
public class ReadWriteLockDemo {

    public static void main(String[] args) {
        Cache cache = new Cache();
        new Thread(new Runnable() {
            public void run() {
                for(int i=1;i<11;i++){

        new Thread(new Runnable() {
            public void run() {
                for(int i=1;i<11;i++){



class Cache{

    private volatile Map<String,Object> map = new HashMap();

    ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    Lock readLock = reentrantReadWriteLock.readLock();
    Lock writeLock = reentrantReadWriteLock.writeLock();

     * Write operation
    public void put(String key,Object value){
            System.out.println("Start writing data, key:"+key+",data:"+value);
            map.put(key, value);
            System.out.println("End of data writing, key:"+key+",data:"+value);
        }catch (Exception e){

        }finally {

     * Read operation
    public Object get(String key){
            System.out.println("Start reading data, key:"+key);
            Object o = map.get(key);

            System.out.println("End of data reading, key:"+key+",Return results:"+o);
            return o;
        }catch (Exception e){

        }finally {
        return null;

Result: start writing data, key:1,data:1
 End of data writing, key:1,data:1
 Start writing data, key:2,data:2
 End of data writing, key:2,data:2
 Start writing data, key:3,data:3
 End of data writing, key:3,data:3
 Start writing data, key:4,data:4
 End of data writing, key:4,data:4
 Start writing data, key:5,data:5
 End of data writing, key:5,data:5
 Start writing data, key:6,data:6
 End of data writing, key:6,data:6
 Start writing data, key:7,data:7
 End of data writing, key:7,data:7
 Start writing data, key:8,data:8
 End of data writing, key:8,data:8
 Start writing data, key:9,data:9
 End of data writing, key:9,data:9
 Start writing data, key:10,data:10
 End of data writing, key:10,data:10
 Start reading data, key:1
 End of data reading, key:1,Return results:1
 Start reading data, key:2
 End of data reading, key:2,Return results:2
 Start reading data, key:3
 End of data reading, key:3,Return results:3
 Start reading data, key:4
 End of data reading, key:4,Return results:4
 Start reading data, key:5
 End of data reading, key:5,Return results:5
 Start reading data, key:6
 End of data reading, key:6,Return results:6
 Start reading data, key:7
 End of data reading, key:7,Return results:7
 Start reading data, key:8
 End of data reading, key:8,Return results:8
 Start reading data, key:9
 End of data reading, key:9,Return results:9
 Start reading data, key:10
 End of data reading, key:10,Return results:10


Keywords: architecture

Added by poknam on Wed, 09 Mar 2022 17:15:24 +0200