Read write lock

Time:2021-9-17

ReadWriteLock

Read write lock

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.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *An exclusive lock (write lock) can only be held by one thread at a time
 *Shared lock (read lock) multiple threads can occupy at the same time
 * ReadWriteLock
 *Read read can coexist
 *Read write cannot coexist
 *Write write can coexist
 */

public class ReadWriteLockDemo {
    public static void main(String[] args) {
//        MyCache myCache = new MyCache();
        MyCacheLock myCache = new MyCacheLock();

        //Write
        for (int i = 1; i <= 5; i++) {
            //Lambda expressions cannot access external variables. We can only perform an intermediate conversion through the final variable
            final int temp = i;
            new Thread(()->{
                myCache.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }

        for (int i = 1; i <= 5; i++) {
            final int temp = i;
            new Thread(()->{
                myCache.get(temp+"");
            },String.valueOf(i)).start();
        }

    }
}

//Locked
class MyCacheLock {
    //Volatile writes to the cache will lock the total thread and cannot be read in the middle of the write process
    private volatile Map<String,Object> map = new HashMap<>();
//    private Lock lock = new ReentrantLock();
    //Using read-write locks: more granular control
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //When saving and writing, you only want one thread to write at the same time
    public void put(String key,Object value) {
//        lock.lock();
        readWriteLock.writeLock().lock();
        try {
            System. Out. Println (thread. Currentthread(). Getname() + "write" + key);
            map.put(key,value);
            System. Out. Println (thread. Currentthread(). Getname() + "write OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    //Everyone can read when taking and reading
    public void get(String key) {
        readWriteLock.readLock().lock();
        try {
            System. Out. Println (thread. Currentthread(). Getname() + "read" + key);
            Object o = map.get(key);
            System. Out. Println (thread. Currentthread(). Getname() + "read OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }

    }
}




/**
 *Custom cache
 */
class MyCache {
    //Volatile writes to the cache will lock the total thread and cannot be read in the middle of the write process
    private volatile Map<String,Object> map = new HashMap<>();

    //Save, write
    public void put(String key,Object value) {
        System. Out. Println (thread. Currentthread(). Getname() + "write" + key);
        map.put(key,value);
        System. Out. Println (thread. Currentthread(). Getname() + "write OK");
    }

    //Take
    public void get(String key) {
        System. Out. Println (thread. Currentthread(). Getname() + "read" + key);
        Object o = map.get(key);
        System. Out. Println (thread. Currentthread(). Getname() + "read OK");

    }
}

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]