Reputation: 3191
I have a Java client (client server app) that does two main things: (1) listen to server to receive files and save them to a local folder and (2) watch that folder for changes and send changes to the server. I want to run each in its own thread. First, is it a good idea to run each task on a separate thread. Second, how do I lock the folder when it's used by either task to avoid interference?
Upvotes: 0
Views: 248
Reputation: 116828
is it a good idea to run each task on a separate thread
It sounds like a good idea to split your program into threads since the 2 tasks can work asynchronously and concurrently. The 1st thread could be downloading at the same time the 2nd one is uploading.
how do I lock the folder when it's used by either task to avoid interference?
I wouldn't do a lock at all. I'd have your 1st thread read a file from the server, write it into the folder, and then add a FileToSend
object (or maybe just a File
object) to a BlockingQueue
. So instead of looking at the directory, your 2nd thread would just be waiting on the BlockingQueue
for files to be sent to the server. The LinkedBlockingQueue
class should work well for this. The BlockingQueue
takes care of the locking for you.
If you do need to share a lock then you could just inject a lock object into your two threads:
private final Object folderLock = new Object();
...
new Thread(new Downloader(folderLock)).start();
new Thread(new Uploader(folderLock)).start();
...
A good pattern would be to define an addFileToUpload(File fileToUpload)
method on your Uploader
class. Then your Uploader
can decide what to do with it. The BlockingQueue
could then be local to the Uploader
Uploader uploader = new Uploader();
// pass the uploader into the downloader
new Thread(new Downloader(uploader)).start();
new Thread(uploader).start();
Upvotes: 4