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 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
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

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

Ryan Raina

Joined: Jun 16, 2010
Posts: 28
Hi All

Consider the following code

[Added code tags - see UseCodeTags for details]


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 every object will have it's own method they should not block here...and every thread get's it's local thread copy..

Any suggestions??
Matthew Brown

Joined: Apr 06, 2010
Posts: 4544

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.

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

Joined: Aug 11, 2007
Posts: 4659

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:
subject: Do I need to have synchronized keyword in the code ???
It's not a secret anymore!