This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
Hi - need a bit of advice. I have a program that moves files from one directory to another (and then does some stuff...). The program has multiple threads running e.g.
//in main XmlCompare xc = new XmlCompare(); Thread t1 = new Thread(xc); t1.start();
XmlCompare xc2 = new XmlCompare(); Thread t2 = new Thread(xc2); t2.start();
The problem is that while one thread is moving a file from dir1 to dir2, no other thread should be able to move a file. But I don't think I can sychronize because I have multiple objects? Or can I? I thought about using some kind of lock, so the first thread sets lockCookie to "locked" and while lockCookie.equals("locked") the second thread cannot move the file. But if I have two XmlCompare objects, and lockCookie is a variable within the XmlCompare class, then each object will have its own instance of lockCookie. So was thinking could write a cookie to a file, delete when done - i.e. external to the actual program, but seems kind of clumsy. Any suggestions on best way to do this?
Also - two more questions - why are threads spawned one per object? i.e. why not have:
XmlCompare xc = new XmlCompare(); Thread t1 = new Thread(xc); t1.start(); Thread t2 = new Thread(xc); t2.start();
Also, I am setting the name using Thread.setName in main, but in run the name always comes out as -1, or -3 or whatever. Why is this?
syncMoveFile is static so there is a single instance of it shared by all instances of the XMLCompare class. By synchronizing on syncMoveFile, only one instance of XMLCompare will be able to run the code in the synchronized block at a time.