Java read-write locks theory and code verification

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/longgeqiaojie304/article/details/90728367

Java read-write locks theory and code verification

1, Java read-write locks theory

Write lock (exclusive lock): means that the lock can only be held by a thread lock. For ReentrantLock and Sychronized are exclusive lock.

Read lock (shared lock): means that the lock can be held by multiple threads. For ReentrantReadWriteLock, which read lock is a shared lock, write lock is an exclusive lock it. Sharing read lock ensures very efficient concurrent read, write, write, read, write processes are mutually exclusive.

2, Java write lock code verification

Demo One: where code is not added to the read-write lock

import java.util.HashMap;

import java.util.Map;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.locks.ReentrantReadWriteLock;

 

/**

 * Multiple threads simultaneously read a resource class time is no problem, so in order to meet concurrency, read the shared resources should be carried out simultaneously.

 * However, if you want to write one thread to share resources, other threads should not have to read or write

 * <p>

 * Summary:

 * Read - coexist

 * Read - write not coexist

 * Write - read not coexist

 * Write - Write not coexistence

 *

 * Writes: + atomic monopoly, the whole process must be a complete whole, the middle can not have any interruption

 */

public class ReentrantReadWriteLockDemo {

    public static void main(String[] args) {

        MyCache myCache = new MyCache();

        for (int i = 0; i < 5; i++) {

            you end = i;

            new Thread(() -> {

                myCache.put(finalI + "", finalI + "");

            }, i + "").start();

        }

 

        for (int i = 0; i < 5; i++) {

            you end = i;

            new Thread(() -> {

                myCache.get(finalI + "");

            }, i + "").start();

        }

 

    }

}

 

class MyCache {

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

 

    //private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

 

    public void put(String key, String value) {

        System.out.println(Thread.currentThread().getName() + "正在写......");

        try {

            TimeUnit.MILLISECONDS.sleep(500);

        } catch (InterruptedException e) {

            e.printStackTrace ();

        }

        map.put(key, value);

        System.out.println (. Thread.currentThread () getName () + "write completed");

    }

 

    public String get(String key) {

        System.out.println(Thread.currentThread().getName() + "正在读......");

        try {

            TimeUnit.MILLISECONDS.sleep(500);

        } catch (InterruptedException e) {

            e.printStackTrace ();

        }

        String value = map.get(key);

        System.out.println (. Thread.currentThread () getName () + "read complete");

        return value;

    }

}

Program execution results are as follows: 0 not finished thread on the thread writes No. 4, No. 3 writes threads, thread 2 and so interrupt the write operation, there is no concurrent increase write lock operation is not safe.

Demo Two: code plus the case where the read-write lock

import java.util.HashMap;

import java.util.Map;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.locks.ReentrantReadWriteLock;

 

/**

 * Multiple threads simultaneously read a resource class time is no problem, so in order to meet concurrency, read the shared resources should be carried out simultaneously.

 * However, if you want to write one thread to share resources, other threads should not have to read or write

 * <p>

 * Summary:

 * Read - coexist

 * Read - write not coexist

 * Write - read not coexist

 * Write - Write not coexistence

 *

 * Writes: + atomic monopoly, the whole process must be a complete whole, the middle can not have any interruption

 */

public class ReentrantReadWriteLockDemo {

    public static void main(String[] args) {

        MyCache myCache = new MyCache();

        for (int i = 0; i < 5; i++) {

            you end = i;

            new Thread(() -> {

                myCache.put(finalI + "", finalI + "");

            }, i + "").start();

        }

 

        for (int i = 0; i < 5; i++) {

            you end = i;

            new Thread(() -> {

                myCache.get(finalI + "");

            }, i + "").start();

        }

 

    }

}

 

class MyCache {

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

 

    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

 

    public void put(String key, String value) {

        rwLock.writeLock().lock();

        System.out.println(Thread.currentThread().getName() + "正在写......");

        try {

            TimeUnit.MILLISECONDS.sleep(500);

        } catch (InterruptedException e) {

            e.printStackTrace ();

        }

        map.put(key, value);

        System.out.println (. Thread.currentThread () getName () + "write completed");

        rwLock.writeLock().unlock();

    }

 

    public String get(String key) {

        rwLock.readLock().lock();

        System.out.println(Thread.currentThread().getName() + "正在读......");

        try {

            TimeUnit.MILLISECONDS.sleep(500);

        } catch (InterruptedException e) {

            e.printStackTrace ();

        }

        String value = map.get(key);

        System.out.println (. Thread.currentThread () getName () + "read complete");

        rwLock.readLock().unlock();

        return value;

    }

}

Program execution results are as follows: 0 threads written following the full implementation of the write operation to complete before the thread numbers 1,3,2,4, a read operation does not need to guarantee atom + exclusive, shared resources can be random read, read to ensure concurrent performance.

Guess you like

Origin blog.csdn.net/longgeqiaojie304/article/details/90728367