[英]Concurrent Processing of csv for multiple users
我有一种情况,我必须处理用户文件夹中的CSV文件,并在处理后将它们存储到数据库中。 每个用户有5种Feed。 任何用户都可以随时在该文件夹中发送任何提要,以进行处理,需要遵循以下规则:
实现此目的的好方法是什么?
可以使用AtomicBoolean的映射来实现第一个限制。 这可能不必是ConcurrentHashMap,因为初始化后您将不会更改地图的键。 完成后,别忘了将提要的值重置为false。
checkAndProcessFeed(Feed feed, Map<String, AtomicBoolean> map) {
while(!map.get(feed.type).compareAndSet(false, true)) // assuming the AtomicBooleans were initialized to false
Thread.sleep(500);
}
process(feed); // at this point map.get(feed.type).get() == true
map.get(feed.type).set(false); // reset the AtomicBoolean to false
}
其他两个限制可以使用AtomicInteger实现,用于维护客户端和每个客户端文件的数量; 处理完成后递减,并通过比较设置递增以启动新的客户端/文件。
final int maxClient = 5;
AtomicInteger clientCount = new AtomicInteger(0);
ConcurrentLinkedQueue<Client> queue = new ConcurrentLinkedQueue<>(); // hold waiting clients
while(true) {
int temp = clientCount.intValue();
if(!queue.isEmpty() && clientCount.compareAndSet(temp, temp + 1) { // thread-safe increment
process(clients.poll()); // don't forget to decrement the clientCount when the processing finishes
} else Thread.sleep(500);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.