aspose file tools*
The moose likes Threads and Synchronization and the fly likes Synchronized methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Synchronized methods" Watch "Synchronized methods" New topic
Author

Synchronized methods

Mark Butcher
Ranch Hand

Joined: Jun 28, 2012
Posts: 46
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
Sergey Korytnikov
Greenhorn

Joined: Sep 14, 2013
Posts: 10

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.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18846
    
  40


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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Sergey Korytnikov
Greenhorn

Joined: Sep 14, 2013
Posts: 10

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.
Chan Ag
Bartender

Joined: Sep 06, 2012
Posts: 1018
    
  15
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

Joined: Jun 28, 2012
Posts: 46
Thank you for the replies. I understood the concept.

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

Thanks,
Mark.
Sergey Korytnikov
Greenhorn

Joined: Sep 14, 2013
Posts: 10

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
Bartender

Joined: Sep 06, 2012
Posts: 1018
    
  15
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

Joined: Jun 28, 2012
Posts: 46
Thanks guys that really helped !!
Anil KumarHn
Greenhorn

Joined: Aug 17, 2013
Posts: 1
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

Joined: Sep 14, 2013
Posts: 10

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.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronized methods