java - Java 使用持久存储实现锁定机制
问题描述
我已经实现了 Groovy / Java JAR 文件,其中包含在移动设备上安装应用程序以及获取安装在移动设备上的应用程序的属性和设备属性的方法。
我想实现一种读写锁定机制,只允许一定数量的用户访问设备。写锁将是:每个移动设备 1 个请求,读锁每个移动设备 10 个请求。
Java Semaphore 似乎是解决这个问题的好方法,允许为读写锁分配大量请求。但我还需要持久存储针对每个设备获取的每个锁的状态。
即使没有信号量,任何关于如何做到这一点的建议都将不胜感激。我预计少于 50 个设备和少于 100 个并发用户请求。
解决方案
您可以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();
}
}
推荐阅读
- java - Java 实例中的泛型设计
- gremlin - 使用 Gremlin.Net 获取请求数据
- android - Flutter - 如何使 DatePicker 中的选定值出现在 TextFormField 中?
- flutter - 本地化 jitsi_meet_flutter
- python - 熊猫四舍五入到最近的第一个月
- java - Spring Boot Client 调用由 OAuth2 保护的 REST API
- javascript - 使用 jQuery ajax 调用在 MVC 视图中绑定部分视图
- java - 使用 GrandID API 登录银行 ID - 瑞典
- sql - SQL Left Join 先匹配
- javascript - 如何避免访问远程服务器时请求的资源上不存在“Access-Control-Allow-Origin”标头