aspose file tools*
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


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "which object will this synchronize on?" Watch "which object will this synchronize on?" New topic
Author

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?

thanx
Peter den Haan
author
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: http://aspose.com/file-tools
 
subject: which object will this synchronize on?
 
Similar Threads
IllegalMonitorStateException
Collections.synchronizedMap Help
vector in vector
Problem with Thread Interaction
WA #1.....word association