Does this synchronize block , provide a lock on all three objects iei "third party", "this" and "anothr object" or only "third party object".
Only the objects that you synchronized will be used as a lock -- there is no magic mechanism that figures out what else to lock.
If it provides only lock for "third party" then any other method which updates "this" object from a non-synchronized method is eligible for modification ?
Synchronization is completely cooperative. For example, if another thread decide to access the "third party" object without synchronizing on it, it can break your app too. There is no magic mechanism that prevents threads that refuse to cooperative to be locked out too.
Here in the above eg, meth1() synchronizes a block on "this" reference, ONLY THIS OBJECT ie current ObjectLocking instance IS SYNCHRONIZED, NOT OBJECT OutsideObject , am i right ?
Since, meth2() is not synchronized nor had any synchronization blocks... any thread which does NOT have lock on "this" object(current ObjectLocking instance) can be invoke this meth2()... right ? , if picked y thread scheduler, of course ...
In this case, if it is picked by the scheduler, will this thread be able to modify the "Outsider Object", since it is the same object passed to meth1() and meth2() but has no synchronization lock on it?
Also, will it be able to update instance variable "x", my assumption is NO, if a thread might have a lock on "this" instance, ie current instance of ObjectLocking, then it will not be able to acess the "x" on the current object from "objectLocking" ?
If you do have some basic rules for synchronization which you think i am missing out on, could you please share it , thanks for the help!
Joined: Jun 09, 2009
Yes, you are correct about what is being locked on.
Meth2 is not synchronized, any other thread can call it at any time. Even if meth2 has been called from synchronized code (say, meth1 for example), any other thread can still call meth2 any any time. In a nutshell, your code is not thread-safe.
Meth2 will be able to change x - why wouldn't it? x is in scope.
You could simply place a synchronized block inside meth2 (or declare the method synchronized), that would stop it updating x at the same time meth1 is running, but that may not be enough. It would still be possible for another thread to interfere between calls to meth1 and meth2. If that is a concern in your design, you should place the calls to meth1 and meth2 inside a synchronized block as well.
Threading can be tricky to get right - the only thing to do is practice, practice, practice. And don't forget about wait(), notify() and notifyAll().