Multiple threads arrive, the last should do the processing

浪子不回头ぞ 提交于 2019-12-25 18:50:41

问题


I'm implementing a logging where multiple threads can write into one List of log. The last thread should write the contents of the List to a file. So the thread which is the last to write into the List should flush the List into a file. What is the best way to accomplish this?

For the List I just need one of the concurrent classes that is efficient for multiple writers and one reader.


回答1:


In my case the simple solution was to implement Closeable and then do the flushing in the close method.




回答2:


My solution:

  1. Decide number of threads ( say N)
  2. Start a CountDownLatch with N as counter
  3. Wait for all threads to populate the value in List ( till count is zero)
  4. Now store the list into file from the main thread if you wish.

    Or

  5. Create a new Thread from main thread and store the list into file.

Refer to below post on usage of CountDownLatch:

How is CountDownLatch used in Java Multithreading?

The only concurrent List collection available in java is : CopyOnWriteArrayList

A thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.



来源:https://stackoverflow.com/questions/44126754/multiple-threads-arrive-the-last-should-do-the-processing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!