首页 > 解决方案 > Java 使用持久存储实现锁定机制

问题描述

我已经实现了 Groovy / Java JAR 文件,其中包含在移动设备上安装应用程序以及获取安装在移动设备上的应用程序的属性和设备属性的方法。

我想实现一种读写锁定机制,只允许一定数量的用户访问设备。写锁将是:每个移动设备 1 个请求,读锁每个移动设备 10 个请求。

Java Semaphore 似乎是解决这个问题的好方法,允许为读写锁分配大量请求。但我还需要持久存储针对每个设备获取的每个锁的状态。

即使没有信号量,任何关于如何做到这一点的建议都将不胜感激。我预计少于 50 个设备和少于 100 个并发用户请求。

标签: javamultithreadinggroovysemaphorekey-value-store

解决方案


您可以ReentrantReadWriteLock使用BlockingQueue. ReentrantReadWriteLock用于允许一个写者,同时BlockingQueue限制N个读者同时读。像这样的东西:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class DeviceHandler
{
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private BlockingQueue<Object> readersQueue = new ArrayBlockingQueue<>(10);

    public void read() throws InterruptedException
    {
        // if queue is full, this blocks until another thread removes an object
        readersQueue.put(new Object());
        // this blocks if another thread acquires the write lock
        reentrantReadWriteLock.readLock().lock();

        // do read action

        reentrantReadWriteLock.readLock().unlock();
        readersQueue.take();
    }

    public void write()
    {
        // this blocks if the read lock is acquired by other threads
        reentrantReadWriteLock.writeLock().lock();

        // do write action

        reentrantReadWriteLock.writeLock().unlock();
    }
}

推荐阅读