Blog 17: Java Concurrent Programming - Lock Mechanism and Synchronization Primitives

Blog 17: Java Concurrent Programming - Lock Mechanism and Synchronization Primitives

Abstract: This article will introduce the lock mechanism and synchronization primitives in Java concurrent programming, including ReentrantLock, ReadWriteLock, StampedLock, Semaphore and other technologies.

In order to ensure data consistency and thread safety in a multi-threaded environment, Java provides a series of lock mechanisms and synchronization primitives. This article will introduce common locking mechanisms and synchronization primitives in Java.

ReentrantLock

ReentrantLock is a reentrant lock that allows the same thread to acquire the lock multiple times. Compared with the synchronized keyword, ReentrantLock provides more advanced features, such as interruptible locks, fair locks, etc.

Example using ReentrantLock:

class Counter {
    
    
    private int count = 0;
    private final ReentrantLock lock = new ReentrantLock();

    public void increment() {
    
    
        lock.lock();
        try {
    
    
            count++;
        } finally {
    
    
            lock.unlock();
        }
    }
}

ReadWriteLock

ReadWriteLock is a read-write lock that allows multiple threads to read shared data at the same time, but only allows one thread to write data. Using ReadWriteLock can improve concurrency performance.

Example using ReadWriteLock:

class DataStore {
    
    
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();
    private Map<String, String> data = new HashMap<>();

    public String read(String key) {
    
    
        readLock.lock();
        try {
    
    
            return data.get(key);
        } finally {
    
    
            readLock.unlock();
        }
    }

    public void write(String key, String value) {
    
    
        writeLock.lock();
        try {
    
    
            data.put(key, value);
        } finally {
    
    
            writeLock.unlock();
        }
    }
}

StampedLock

StampedLock is a new lock mechanism introduced by Java 8. It provides an optimistic read lock strategy that can improve concurrency performance in some scenarios. It should be noted that StampedLock does not support reentrancy.

Example using StampedLock:

class Point {
    
    
    private double x, y;
    private final StampedLock lock = new StampedLock();

    public void move(double deltaX, double deltaY) {
    
    
        long stamp = lock.writeLock();
        try {
    
    
            x += deltaX;
            y += deltaY;
        } finally {
    
    
            lock.unlockWrite(stamp);
        }
    }

    public double distanceFromOrigin() {
    
    
        long stamp = lock.tryOptimisticRead();
        double currentX = x;
        double currentY = y;
        if (!lock.validate(stamp)) {
    
    
            stamp = lock.readLock();
            try {
    
    
                currentX = x;
                currentY = y;
            } finally {
    
    
                lock.unlockRead(stamp);
            }
        }
        return Math.sqrt(currentX * currentX + currentY * currentY);
    }
}

Semaphore

A semaphore is a counting semaphore that limits the number of concurrent accesses to a shared resource. Semaphore is usually used to implement scenarios such as resource pools and flow control.

Example using Semaphore:

class ConnectionPool {
    
    
    private static final int MAX_CONNECTIONS = 10;
    private final Semaphore semaphore = new Semaphore(MAX_CONNECTIONS, true);
    private final Set<Connection> connections = new HashSet<>();

    public Connection acquire() throws InterruptedException {
    
    
        semaphore.acquire();
        synchronized (connections) {
    
    
            Connection connection = createConnection();
            connections.add(connection);
            return connection;
        }
    }

    public void release(Connection connection) {
    
    
        synchronized (connections) {
    
    
            connections.remove(connection);
        }
        semaphore.release();
    }

    private Connection createConnection() {
    
    
        // 创建连接逻辑
        return null;
    }
}

Summarize

This article introduces the lock mechanism and synchronization primitives in Java concurrent programming, including ReentrantLock, ReadWriteLock, StampedLock, Semaphore and other technologies. By mastering these lock mechanisms and synchronization primitives, you can write more efficient and stable concurrent programs.

In the next blog, we will introduce atomic operations and concurrent containers in Java concurrent programming. Stay tuned!

Guess you like

Origin blog.csdn.net/m0_61821405/article/details/130588768