【问题标题】:Java Implement locking mechanism with persistent storageJava 使用持久存储实现锁定机制
【发布时间】:2020-02-19 16:47:49
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: java multithreading groovy semaphore key-value-store


    【解决方案1】:

    您可以将ReentrantReadWriteLockBlockingQueue 一起使用。 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();
        }
    }
    

    【讨论】:

    • 非常感谢 Eng,感谢您使用 ReentrantReadWriteLock 和 BlockingQueue 的实用程序建议,以及您对我的用例的说明性示例。最好的问候,
    猜你喜欢
    • 2016-09-17
    • 2013-10-19
    • 2011-07-17
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多