• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

locking with multiple objects

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic