This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "locking with multiple objects" Watch "locking with multiple objects" New topic
Author

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);
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?

All advice appreciated.

Thanks

L
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3419
    
  12


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.


Joanne
 
Consider Paul's rocket mass heater.
 
subject: locking with multiple objects
 
Similar Threads
Livelock same as race condition?
regding Thread.join
How can i start multiple threads ??
Thread behavior with synchronized method
about threads, using locks of the objects in synchronized blocks