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??
}
}
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.
Yes, the unsynchronized methods can be accessed/called by any Thread, that has/gets the reference to the same instance.
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.
Yes. Other methods can access non-synchronized methods.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With