Thursday, March 22, 2007

Threads in Java

Synchronization:
Locking is about coordinating the activities of two or more threads, so they can work together and not collide in their use of the same address space. Synchronization makes sure only one thread at a time can perform certain activities that manupulate an object.

In Java
Every Class has a lock
Every instance has a lock.

To synchronize a method:
synchronized void say () {/*do sth*/ }
Because say() is an instance method, a thread has to acquire the lock on the particular instance before it can invoke the say() method.
If say() were a class (static) method instead of an instance method, we could still mark it as synchronized. But in this case as there is no instance object involved, the lock would be on the class object itself

No comments: