问题
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:
- Decide number of threads ( say N)
- Start a CountDownLatch with N as counter
- Wait for all threads to populate the value in List ( till count is zero)
Now store the list into file from the main thread if you wish.
Or
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