• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Synchronized methods

 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey guys,

I have written a simple code to learn synchronized methods.
Here two threads are accessing one synchronized method as below :


OUPUT :
----------
THREAD NAME : ONE
THREAD NAME : TWO
----------

Now, my doubt here is how can the two threads(one & two) access the synchronized method at the same time.
Whereas a synchronized method can be accessed by a single thread at a time.

Thanks,
Mark
 
Greenhorn
Posts: 11
Eclipse IDE Slackware Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Nohow, it's the primary goal of synchronized statement. But you may minimize locking time by using syncronized(obj) {..} statement to lock critical resource.
For example, in your case you may save on sleeping time:


As alternative solution, you may move your Thread.sleep(..) code to another non-synchronized method.
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Synchronization is based on objects -- not classes or methods. If two threads synchronize on the same object, they will block on each other -- otherwise, they will not.

In the OP's example, the two threads are synchronizing using different objects -- this is why they both print their thread names immediately, even though they hold their locks for a long time.

Henry
 
Sergey Korytnikov
Greenhorn
Posts: 11
Eclipse IDE Slackware Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Henry Wong wrote:
Synchronization is based on objects -- not classes or methods. If two threads synchronize on the same object, they will block on each other -- otherwise, they will not.
Henry



I agree with you on this, I think I was confused with original question. It seems that your answer is what Mark looking for.
 
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

For example, in your case you may save on sleeping time:
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
private static Object monitor = new Object();
public void method() {
synchronized (monitor) {
// Things to synchronize here..
System.out.println("THREAD NAME : " + Thread.currentThread().getName());
}
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}


As alternative solution, you may move your Thread.sleep(..) code to another non-synchronized method.



I think 'you may save on sleeping time' is misleading. A synchronized block just gives you more flexibility ( and often shorter lock scope - it can be longer also if you call multiple methods in a synchronized block ) in locking compared to synchronized methods. Also Thread.sleep() may/may not be a piece of code that can be moved in/out of the lock scope - it depends on the locking requirement.

Edit - Yeah, for the current code splitting off Thread.sleep() from the synchronized method doesn't harm and it may reduce the lock scope sometimes without increasing synchronization, but I make my last point just so people reading this thread don't misunderstand this as a solution to reduce lock scope for every case.

 
Mark Butcher
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for the replies. I understood the concept.

But then in what scenario should one use synchronized methods ??

Thanks,
Mark.
 
Sergey Korytnikov
Greenhorn
Posts: 11
Eclipse IDE Slackware Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mark Butcher wrote:But then in what scenario should one use synchronized methods ??



Synchronized keyword, when used with method, is equal to synchronized(this) {..}. In your case you have 2 separate objects (each per thread), so you have 2 separate locking resources as 'this'. To have only one synchronized method (actually, synchronized code) you should: 1) instantiate one object with synchronized method which is shared between 2 threads; 2) or make synchronized method as static.
 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think Henry has already answered this question.

Since you've asked it again -

We know that objects have a state. Threads are objects that may access other objects through whatever code is executed in their run method. Now there are two kinds of objects here - the thread object and the object that the thread accesses. If you have multiple threads accessing the same object concurrently in a way that may make the state of the object ( the object the thread is accessing via its run method ) inconsistent, we need to control the access to the object in question so that reads and writes ( on the object ) are consistent.

How does a thread access an object? Through its methods. So when we make a method synchronized, we ensure that at a time only one thread can be in that method of an object. Other threads that have invoked the same method on the same object need to wait till the first thread is done and the scheduler allocates CPU to the next thread. Methods are coded in a class and a class has many objects. Synchronization is about controlling access to a resource ( an object ) in contention.

We have two kinds of methods. Instance methods and static methods. With synchronized instance methods, the thread that invokes the instance method first ( depending on the scheduling algorithm - let's assume it is the first thread always ) gets an exclusive lock on the object to run its synchronized instance methods. Static methods are associated with class object. So with static synchronized methods, the thread that invokes the static synchronized method first ( again depending on the scheduling algorithm ) gets an exclusive lock on the class object to run its synchronized static methods. Others have to wait till the first one is done.

In your first post, you have two different objects and hence instance level synchronized methods are no help. In the other suggested code, there is a static object created and a synchronized block locks that static object. So the effect is that no threads, despite the object they are accessing, can access that synchronized block concurrently.

Now answer on when to use synchronized methods is a topic that spans many considerations. But if you want a simple locking idiom, synchronized methods are good. There is more to know on this. But you may want to explore a little bit about how wait/notify works, how exceptions are handled and such things before that. So more on that later. Or deferred to somebody who can explain it in short..

To keep it simple ( and ignoring other locking idioms for now ), you code synchronized methods when you want to keep it simple, the synchronized methods suffice the locking need, and it is the instance or the class object ( something that constitutes their state ) in contention . You know that with synchronized blocks you can lock any other object as well and the scope of the lock is not default - the size of the method.

 
Mark Butcher
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks guys that really helped !!
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If am not wrong synchronized method are mainly used to avoid deadlock situation where one object may use resource of other object .Even if we use sleep() lock is not released until the object completes its execution.
Correct me if am wrong.
 
Sergey Korytnikov
Greenhorn
Posts: 11
Eclipse IDE Slackware Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Anil KumarHn wrote:If am not wrong synchronized method are mainly used to avoid deadlock situation where one object may use resource of other object .Even if we use sleep() lock is not released until the object completes its execution.
Correct me if am wrong.


Actually, you can get dead-lock with synchronized methods as well, if e.g. two threads performing the code from methods of 2 objects with cross links to another synch methods of other. There can be a lot of situations where you can easily get dead-lock, it's primarily depends on the architecture.
See my raw example below. If Thread 1 and 2 will enter to perform() method of each class in the same time, they will wait forever if A and B references are shared.

 
reply
    Bookmark Topic Watch Topic
  • New Topic