-1

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.

Roland
  • 7,525
  • 13
  • 61
  • 124
  • Your question is a bit too unspecific to be answerable. For example, how would a thread know that it's the last one? – Rolf Schäuble May 23 '17 at 08:59
  • @RolfSchäuble That's part of the problem. A thread should attempt to write to the file. Subsequent threads should do the same but not write to the file what has already been written. So the logic would be: write unless there are other threads queing up. In that case the last thread in the queue should write. – Roland May 23 '17 at 10:28
  • @Roland why not let each thread write its data (whatever that data is) to the file, and synchronize file access to avoid interleaving writes? If that's not possible, more details about your scenario would be helpful. It's still quite vague. – Rolf Schäuble May 23 '17 at 11:14
  • @RolfSchäuble That's what I'm currently doing. But file access is slow, so I would rather synchronize on something other than file access. – Roland May 23 '17 at 11:15
  • @Roland if the individual writes to the file are slow, you could wrap the FileOutputStream with a BufferedOutputStream (if it's still too slow even with buffering, then a more complicated solution most probably won't make it faster). Alternatively, your threads could put their data into a queue which is periodically (e.g. once every second) written out. If this is acceptable under your circumstances, I'd go for that. The long term maintenance costs would definitely be lower than with a solution that tries to synchronize an arbitrary number of threads. – Rolf Schäuble May 23 '17 at 11:33

2 Answers2

0

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

Roland
  • 7,525
  • 13
  • 61
  • 124
-1

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.

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211