The Artima Developer Community
Sponsored Link

Java Answers Forum
Synchronization in Java

1 reply on 1 page. Most recent reply: Nov 3, 2003 4:01 AM by Joe Parks

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Swarup

Posts: 1
Nickname: vaswarup
Registered: Jun, 2003

Synchronization in Java Posted: Nov 3, 2003 3:48 AM
Reply to this message Reply
Advertisement
Hi,

Can somebody clarify a long standing question of mine related to synchronized keyword in Java. Let me explain the way I understand it(correct me if am mistaken).....

The synchronized keyword is used to obtain a lock on an object mentioned in the synchronized line, i.e. 'synchronized (someObj)' means lock on 'someObj'. This 'someObj' can also be 'this'. Also in Java I can synchronize a method by saying (say) 'public synchronized void someMethod().....'

In this case is the lock obtained implicitly on 'this' object? If so, then it means synchronizing a method and writing 'synchronized(this)', is equivalent, right?

If the above statements are true then this would mean that if I have a object which has synchronized methods, then only one method at a time can be invoked on the object. Eg. RMI server object (class that extends UnicastRemoteObject).

And finally, if I assume that the above statements are true and I consider a a weird case where I have a class that has to have synchronized methods and there are no fields in that class (static or non static). Also my methods are not dependent on each other. Then the best way would be to have an object for each method in the class where the purpose of the object would be just to act as the one on which a lock for that method is obtained.

Please let me know your comments.


Joe Parks

Posts: 107
Nickname: joeparks
Registered: Aug, 2003

Re: Synchronization in Java Posted: Nov 3, 2003 4:01 AM
Reply to this message Reply
> if I have a object which has synchronized methods, then
> only one method at a time can be invoked on the object.

Only one synchronized method can be invoked at a time. Non-synchronized methods will not be blocked.

> there are no
> fields in that class (static or non static). Also my
> methods are not dependent on each other.

My first thought is that the methods should be in different classes. Each class should have one clear responsibility, and it sounds like the one you're describing has many responsibilities.

Flat View: This topic has 1 reply on 1 page
Topic: Dividing 2 double values Previous Topic   Next Topic Topic: RMI version Compatibility

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use