Read-write lock

ReadWriteLock

package com.chao.re;
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;

/** * Exclusive locks (write locks) can only be held by one thread at a time, * shared locks (read locks) can be held by multiple threads at the same time * ReadWriteLock * Read - Read can coexist! * Read-write cannot coexist! * Write - Write cannot 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++) {
            final int temp = i;
            new Thread(()->{
                myCache.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }
        / / read
        for (int i = 1; i <=5 ; i++) {
            final int temp = i;
            new Thread(()->{
                myCache.get(temp+""); },String.valueOf(i)).start(); }}}/ / lock
class MyCacheLock{
    private volatile Map<String,Object> map = new HashMap<>();
    // Read/write locks: more fine-grained control
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    //private Lock lock = new ReentrantLock();
    // When writing, only one thread is expected to write simultaneously
    public void put(String key,Object value){
        //lock.lock();
        readWriteLock.writeLock().lock();

        try {
            System.out.println(Thread.currentThread().getName()+"Written"+key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"Write" OK "to");
        } catch (Exception e) {
            e.printStackTrace();
        } finally{ readWriteLock.writeLock().unlock(); }}// Take, read, anyone can read!
    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{
    private volatile Map<String,Object> map = new HashMap<>();
    / / save, write
    public void put(String key,Object value){
        System.out.println(Thread.currentThread().getName()+"Written"+key);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"Write" OK "to");
    }
    / / get read
    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"); }}Copy the code