Synchronized means :- It will allow only one thread at time right? That mean output will come AAAAAAAAAAAAAAAAAAAA 100times and BBBBBBBBBBBBBBBBB 100 times and CCCCCCCCCC times. What is the problem here,
Synchronization is to manage access to data from multiple threads. Some classic example is web hit counter, where you have 1 object that keep track of the number of visits but you have multiple threads of request/servlet which tries to increment the same instance of the counter object.
The example that you have is not working because each test has their own instance of data that they manipulate. So what you see is behavior of standard thread-based operation where you have multiple threads doing their own thing that are being managed by JVM where each thread has its own chance to run.
Do some Google search, there are plenty of tutorials on concurrent programming which give clear example what synchronization do. [ May 08, 2008: Message edited by: Wirianto Djunaidi ]
In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in method level (coarse grained lock � can affect performance adversely) or block level of code (fine grained lock). Often using a lock on a method level is too coarse. Why lock up a piece of code that does not access any shared resources by locking up an entire method. Since each object has a lock, dummy objects can be created to implement block level synchronization. The block level is more efficient because it does not lock the whole method.
Originally posted by arulk pillai: Often using a lock on a method level is too coarse.
In general a fine grained lock is good to have when the lock contention is high. However, when the lock contention is less then it is better to keep it simple. Fine grained locks make the code a little cluttered/hard to decide the sync boundaries and has scope for bugs that are hard to debug. It is like worrying about saving resource which no one else is actually using. [ May 09, 2008: Message edited by: Nitesh Kant ]