File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes which object will this synchronize on? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "which object will this synchronize on?" Watch "which object will this synchronize on?" New topic

which object will this synchronize on?

Daniil Sosonkin
Ranch Hand

Joined: Jan 15, 2004
Posts: 76
hmmm, a question, would this make sence?

As I understand, there wouldn't be a deadlock or memory leak. Can any of you experts trash my understanding or confirm it?

Peter den Haan
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
No, it doesn't quite make sense yet...
Please code to interface (List) rather than implementation.
I'm missing a wait condition here. Also, given that you notify() and not notifyAll(), make sure that you check the condition before launching into a wait().
But this is the killer. All wait()ing threads are waiting on the old messages object now, never to be woken up What you should do is eitherOr perhaps not synchronize on the messages list at all, but on the object which wraps it. The latter would probably be my preference as you could use easier-to-read synchronized methods.

- Peter
Daniil Sosonkin
Ranch Hand

Joined: Jan 15, 2004
Posts: 76
Thanks! Frankly, I don't know where my brain was See, this is a the advantage of C++ - you explicitly have to deallocate an object and thus you know where you loose the reference. In Java, not much attention payed so one does really stupid stupid things.

What I have now is two objects: ArrayList messages and Object lock. And synchronize/wait/notify on lock object. In my case one thread adds messages while another sends them out. There can be a lot of messages, so I don't want to copy them from one object to another and rather create whole new object. Thats why I synchronize:

and now its waiting on the lock:

Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

advantage of c++? If this were c++ it would fail in exactly the same way, except as a bonus you get a memory leak

anyway. you should always use a seperate lock object. Some list implementations, particularly the synchronized ones may take acception to you using them as the monitor. treat your lock as any other object, and do not expose it to the public, only those that require it.
I agree. Here's the link:
subject: which object will this synchronize on?
It's not a secret anymore!