jQuery in Action, 3rd edition
The moose likes Threads and Synchronization and the fly likes locking with multiple objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "locking with multiple objects" Watch "locking with multiple objects" New topic

locking with multiple objects

Laura Williamson
Ranch Hand

Joined: Apr 28, 2004
Posts: 44
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);

XmlCompare xc2 = new XmlCompare();
Thread t2 = new Thread(xc2);

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);
Thread t2 = new Thread(xc);

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?

All advice appreciated.


Joanne Neal

Joined: Aug 05, 2005
Posts: 3742

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.

I agree. Here's the link: http://aspose.com/file-tools
subject: locking with multiple objects
It's not a secret anymore!