Chooti Baba wrote:
> what is the meaning of the following statements:
> synchronized(lock1)
> synchronized(lock2)
>
>
> I have come across the keyword "synchronized" in blocks/methods,
> but this particular type of "declaration" is confusing me which
> I never came across. Can anyyone please explain me in
> "plain English" the purpose of having a reference within
> brackets next to the keyword "synchronized".
>
If you synchronize a method, the JVM locks on the object's monitor. This
prevents any thread except the one owning the lock from entering any
synchronized block in that object. However, you can localize the locks
to the bare minimum necessary to prevent deadlock and starvation. To do
this, you use the form of synchronization you see in that example.
Typically you will have a method 20-30 lines long and only a small
portion will be synchronized because in reality you are more concerned
about locking on a variable than the object as a whole. Additionally,
you can lock on objects other than "this" which is what you see here.
The objects are just regular Object instances that exist solely for
synchronization.
The Java 1.5 way to do this, however, is through the concurrency
framework. You would create an instance of ReentrantLock that behaves
similar to the "synchronized" keyword but is far more flexible and
offers superior performance (although still slower than code that does
not use locking). There are other locks but that one is probably what
most people need most of the time.
Additionally, there are atomic variable types. In this example you do
not need any locking or synchronization: you would simply create an
AtomicInteger and use its methods to alter it. If two threads happen to
modify it at the same time, the enclosing class guarantees that the
updates are atomic: you will not have the subtle issues that can happen
sometimes where you may lose an update and the counter only increments
once. Behind the scenes it uses locking, but this is transparent to the
user of the variable. You do not need to maintain the locks, it is
encapsulated for you.
I use the concurrency classes for all new code I write that needs to be
thread-safe. As I go through old code I at least do the bare minimum of
adding Lock classes rather than using the synchronized keyword. There
are more optimizations to be done but I prefer not to break code unless
I know I can fix it :-)
--
John Gaughan