![]() |
Interesting fact about synchronized method.
Code:
class ACalled 1 Time Called 2 Time (Synchronized)X= 2 (Synchronized)X= 2 Although it should be, Called 1 Time (Synchronized)X= 2 Called 2 Time (Synchronized)X= 2 I don't understand the o/p, because I think if a synchronized method is invoked for the first time, it won't get executed for the 2nd until the first invocation returns the control....is it right? |
a1 and a2 are running through b1 and b2. These are threads of their own, so you are not doing anything to block the other objects, so issuing a sleep on that running thread won't impact another thread. There are many ways to do this from the simple implicit locks of the object, to running with ExecutorService and pools or writing your own threads and runnables. But you'll need to write the blocking conditions for the thread.
|
Quote:
I guess when a synchronized method is called by the same reference for the 2nd time then it serializes it(blocks it until the first call returns control)...In the above case, I have used different references(a1 and a2) and although they call the same method they are allow concurrent access without synchronization.:) Correct if I am wrong |
Uh, no. The synchronized functionality in Java's purpose is to maintain integrity of an instance of an object, not multiple instances of an object. Multiple threads is of course the purpose, but when each of these threads has an instance of their own to work with, then there is no impact of using the synchronization functionality from one object into the next object. Synchronized can also be done on static methods as well as blocks (my preference if I run synchronized).
So in short, its purpose is to handle mutual access to a shared object. Give both instances of new B call the a1, and it will run as you expect. To implement shared handling on the class itself, you need to handle the threading at a higher level including using locks. |
| All times are GMT +1. The time now is 01:23 AM. |
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.