Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronising twice on the same object?

I was wondering if in Java I would get any odd behaviour if I synchronise twice on the same object?

The scenario is as follows

pulbic class SillyClassName {      object moo;     ...     public void method1(){         synchronized(moo)         {             ....             method2();             ....         }     }      public void method2(){         synchronized(moo)         {             doStuff();         }     } } 

Both methods use the object and are synchronised on it. Will the second method when called by the first method stop because it's locked?

I don't think so because it's the same thread but I'm unsure of any other odd results that might occur.

like image 993
Omar Kooheji Avatar asked Oct 30 '08 11:10

Omar Kooheji


People also ask

Can two synchronized methods run at the same time?

Yes, they can run simultaneously both threads. If you create 2 objects of the class as each object contains only one lock and every synchronized method requires lock.

Can two threads call two different synchronized instance methods of an object?

Can two threads call two different synchronized instance methods of an Object? No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.

What are the two Synchronisation methods?

There are two types of thread synchronization mutual exclusive and inter-thread communication.

What is multithreading synchronization?

Synchronization in java is the capability to control the access of multiple threads to any shared resource. In the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent results. The synchronization is necessary for reliable communication between threads.


1 Answers

Reentrant

Synchronized blocks use reentrant locks, which means if the thread already holds the lock, it can re-aquire it without problems. Therefore your code will work as you expect.

See the bottom of the Java Tutorial page Intrinsic Locks and Synchronization.

To quote as of 2015-01…

Reentrant Synchronization

Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.

like image 79
Leigh Avatar answered Sep 21 '22 05:09

Leigh