有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多用户csv的java并发处理

我有一个场景,我必须为用户处理文件夹中的CSV文件,并在处理后将其存储到数据库中。我们每个用户有5种类型的提要。 任何用户都可以发送该文件夹中的任何提要,任何时候进行处理,需要遵循以下规则:

  • 同一客户端的同一类型提要不能同时处理,这意味着必须始终阻止同时处理时间
  • 不允许跨多个“x”客户端进行并发处理
  • 不允许为同一客户端同时处理多个“y”文件

实现这一目标的好方法是什么


共 (1) 个答案

  1. # 1 楼答案

    第一个限制可以通过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);
    }