Hi all, My project is a webapplication using java/jsp/struts. My requirement is to write bulk data to a file, which i want to run as a separate thread. Since it runs as a separate thread the control comes back to UI (userInterface) page. On subsequent request from UI page by the user i want to check whether the thread process is completed or not , so that i can read from the file. Is it possible to simultaneously read from the file when the thread is in the process of writing data to the file. If so any idea on how to implement this functionality in java? How to keep track of the separate thread (whether it is completed or not) in java? Is it possible to read from the file when the thread is writing to the file in java? Thanks is advance.
1) How to keep track of a Thread to see if it is completed?
There are a handful of ways to do this. The easiest is to put some token in the user's session that indicates the thread is still running. When the thread finishes up it removes that token from the session, so when the next request looks for it, it is gone.
A similar approach would be to use a java.util.concurrent.Future object as the token. The thread would be started using the tools inside the java.util.concurrent package, and the Future generated by starting the thread would be stored for the user to access. Then you can check on it to see if it is done, or if it was canceled or failed for some reason.
2) How to read from a file as it is being written?
Generally I would say you can't do this. A writing thread would lock access to the file preventing another thread from opening it. You may be able to use java.nio mapped FileChannels for this purpose but you would have to be real careful to make sure the positional cursors are tracked properly. Otherwise you may end up writing to the position where you are reading from.
You should look into java.nio, MappedByteBuffers, FileChannels, and perhaps using a CharBuffer as a view on the MappedByteBuffer.
Joined: Aug 09, 2008
Hi Steve, Thanks a lot for your reply. Actually my question regarding thread tracking is, i start a separate thread in strtus Action class and don't join it to the main thread and the control returns back to the UI jsp in browser. Now my question is how to keep track of this separate thread whether it is completed or not to check the file write status.