Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to call a synchronized method from another synchronized method?

If a synchronized method calls another synchronized method, is it thread safe?

void synchronized method1() {      method2() }  void synchronized method2() { } 
like image 435
user705414 Avatar asked Apr 27 '11 02:04

user705414


People also ask

Can two threads call two different synchronized methods of the same class?

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. So if you want to run simultaneously, create two objects and then try to run by using of those object reference.

What will happen if a synchronized method is called by two threads?

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 will happens if a synchronized method is called?

When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Which method can be called by synchronized method?

The synchronized keyword can be used to mark four different types of blocks: Instance methods. Static methods. Code blocks inside instance methods.


1 Answers

Yes, when you mark methods as synchronized, then you are really doing this:

void method1() {     synchronized (this) {         method2()     } }  void method2() {     synchronized (this) {     } } 

When the thread call gets into method2 from method1, then it will ensure that it holds the lock to this, which it will already, and then it can pass through.

When the thread gets directly into method1 or method2, then it will block until it can get the lock (this), and then it will enter.

As noted by James Black in the comments, you do have to be aware with what you do inside of the method body.

private final List<T> data = new ArrayList<T>();  public synchronized void method1() {     for (T item : data) {         // ..     } }  public void method3() {     data.clear(); } 

Suddenly it's not thread safe because you are looking at a ConcurrentModificationException in your future because method3 is unsynchronized, and thus could be called by Thread A while Thread B is working in method1.

like image 135
pickypg Avatar answered Oct 05 '22 17:10

pickypg