Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if i call a non synchronized method from my synchronized method is non synchronized method thread safe?

I i make a call to noonsynchronized method from within my synchronized method is it thread safe?

I have 2 methods as follows:

public class MyClass{

 void synchronized doSomething1(){

   doSomething2();
  }

void doSomething2(){
 //will this block of code be synchronized if called only from doSomething1??
 }

}
like image 473
akshay Avatar asked Sep 24 '11 08:09

akshay


People also ask

Can a threads access non-synchronized method same time?

A thread can run an unsynchronized method of an object even if the object is locked. That's because the object isn't checked for a lock unless a synchronized method is executed. You should use synchronized methods whenever two or more threads might execute the same method.

Can a threads call a non-synchronized instance methods of an object?

Yes, the unsynchronized methods can be accessed/called by any Thread, that has/gets the reference to the same instance.

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

Yes , we can call any number of synchronized method within any synchronized method , it will work as stack how normal method works because when we make any method as synchnonized then lock is over class and thread which owns this lock is running all these methods so there is mens of conflict.. hope u get the answer.

Can synchronized method invoke non-synchronized method?

Yes. Other methods can access non-synchronized methods.


1 Answers

If doSomething2() is only called from doSomething1(), then it will only be called by a single thread for a single instance of MyClass. It could still be called from different threads at the same time, via different instances - so if it acts on any shared data which may not be specific to the instance of MyClass, it's still not guaranteed to fix all threading issues.

Basically, you need to think carefully about any mutable shared state used by multiple threads - there are no easy fixes to that, if you need mutable shared state. In your particular case you'd also need to make sure that doSomething2() was only called from doSomething1() - which would mean making it private to start with...

like image 192
Jon Skeet Avatar answered Oct 25 '22 06:10

Jon Skeet