aspose file tools*
The moose likes Threads and Synchronization and the fly likes Do I need to have synchronized keyword in the code ??? 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 "Do I need to have synchronized keyword in the code ???" Watch "Do I need to have synchronized keyword in the code ???" New topic
Author

Do I need to have synchronized keyword in the code ???

Ryan Raina
Greenhorn

Joined: Jun 16, 2010
Posts: 28
Hi All

Consider the following code

[Added code tags - see UseCodeTags for details]


Output

A about to wait.
B about to wait.
A interrupted.
A terminating.
B interrupted.
B terminating.


my question is that do i need to have synchronized keyword here is the run method..It looks like I need that but I want to understand why??

I am calling run method on two different objects..so every object will have it's own method copy..so they should not block here...and every thread get's it's local thread copy..

Any suggestions??
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4244
    
    7

The reason is your call to wait(). If you look at the Javadocs for java.lang.Object#wait(), you'll see:
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws:
IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.


The thread owns an object's monitor if it's in code synchronized on that object. So if you took out the synchronized keyword you'd get an IllegalMonitorStateException.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4639
    
    5

Are you asking if you need the keyword "synchronized"? or do you need something to synchronize (mutex) your code?

In the beginning, the only way to write thread safe code was to use the keyword "synchronized"

Java 5 implemented a number of new classes and methods for synchronization, so you can use things like ReadWriteLock and achieve the same effect. So the keyword is not the only way to do it, but you must write thread safe code if you use threads.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Do I need to have synchronized keyword in the code ???
 
Similar Threads
Calling wait()/ notify() in run()
Please Explain The Output.
notifyAll()
Interrupt, Interrupted and isInterrupted
Regarding Join method in Threads