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?
Share
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.
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
FileToSendobject (or maybe just aFileobject) to aBlockingQueue. So instead of looking at the directory, your 2nd thread would just be waiting on theBlockingQueuefor files to be sent to the server. TheLinkedBlockingQueueclass should work well for this. TheBlockingQueuetakes 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:
A good pattern would be to define an
addFileToUpload(File fileToUpload)method on yourUploaderclass. Then yourUploadercan decide what to do with it. TheBlockingQueuecould then be local to theUploader