我是多线程技术的新手,所以很感谢任何人对我是否做对了事情的建议。
我需要执行以下操作:
预处理传入的消息,并将其压入<<数据结构。我使用了HashMap,将消息的UUID作为 key ,并将消息本身作为值>>用于随机访问。对于此消息状态的任何其他请求都将以UUID的形式发送,然后可以从 map 中检索该UUID以进行随机访问。
同时,我需要另一个线程,该线程将按插入顺序顺序访问值(或消息),并对其进行处理
因此,这是在类商店中操作Map的第一步
public class Store {
static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
static Map<String, MessageFileRead> fileGeneratorMap = Collections.synchronizedMap(new LinkedHashMap());
public static boolean insertRecord(MessageFileRead messageFileRead) {
boolean processed = false;
lock.writeLock().lock();
try {
if (!fileGeneratorMap.containsKey(messageFileRead.uuid)) {
fileGeneratorMap.put(messageFileRead.uuid, messageFileRead);
processed = true;
}
} finally {
lock.writeLock().unlock();
}
return processed;
}
public static boolean updateRecord(String uuid, Status status) {
boolean processed = false;
lock.writeLock().lock();
try {
if (fileGeneratorMap.containsKey(uuid)) {
fileGeneratorMap.get(uuid).status = status;
processed = true;
}
} finally {
lock.writeLock().unlock();
}
return processed;
}
public static boolean deleteRecord(String uuid) {
boolean processed = false;
lock.writeLock().lock();
try {
for (final Iterator<Map.Entry<String, MessageFileRead>> it = fileGeneratorMap.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, MessageFileRead> entry = it.next();
if (entry.getKey().equals(uuid)) {
it.remove();
break;
}
}
} finally {
lock.writeLock().unlock();
}
return processed;
}
这是使用迭代器顺序访问映射的代码,该迭代器位于同一包中另一个类的另一个线程中。这是在方法中,该方法是调用新工作线程的框架代码的一部分。
while (!stopped) {
try {
Store.lock.writeLock().lock();
for (final Iterator<Map.Entry<String, MessageFileRead>> it = Store.fileGeneratorMap.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, MessageFileRead> entry = it.next();
MessageRead message = entry.getValue();
if (message.status != COMPLETED) {
JSONObject response = DbService.process(message);
// And the above process method internally calls the updateRecord with a status of COMPLETED so that this message is marked as COMPLETED processing and is not picked up in the next run.
}
}
} finally {
Store.lock.writeLock().unlock();
}
}
到目前为止,我还没有遇到任何问题,但是它仍然处于起步阶段,我想知道我做的是否正确,因此欢迎您提出任何建议/建议。
最佳答案
当ConcurrentHashMap可用时,我会质疑Collections.synchronizedMap的使用,并且您可以避免显式锁定 map 。
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html
关于java - 多线程中的共享锁-Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37661649/