File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Multiple threads writing concurrently to same file [Again!]

 
Tom Johnson
Ranch Hand
Posts: 142
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
Having read an extensive discussion on the new java.nio package here on java ranch
here
, I have concluded that nio package does not give support for ASYNCHRONOUS/NON BLOCKING writing to the file.

Following a search of the web I have seen multiple places where others have concluded the same : e.g.
example
"Java NIO doesn't support non-blocking file IO. Only non-blocking socket
IO. If you look you'll see that the FileChannel does not extend the
SelectableChannel and so cannot be set to non-blocking mode or
registered with a selector."

So, my question is :
Does anyone have anyone have any ideas how multiple threads can write to the same file at the same time without blocking while writing? Or is this actually even possible?!
The reason behind this is that i have many worker threads which may need to log data to an infoLog file at anytime during their execution and I want them to be as optimized (ie non blocking) as possible.

Thanks in advance
Tom
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use a standard producer/consumer mechanism. Multiple threads would add write requests to a queue, and one dedicated thread would pull them off the queue and write them to the file.
 
Tom Johnson
Ranch Hand
Posts: 142
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent answer, as you say using simple wait() notifyAll() will allow me to add in data from multiple threads to the write queue and then remove the date in a dedicated other thread when notifed.

Thanks!!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic