Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Synchronization context In Java

All of you know the synchronization context in Java that they are can be

  • on the instance.
  • on the java.lang.Class instance for a certain loaded class.
  • on a given object

And I need to ask; When i write

Dimension d = new Dimension();

synchronized(d){
  // critical atomic operation
}

synchronization of a given object equal to synchronization on the instance practically.

so when I write synchronized(d) where d is an instance of object, then the thread will gain the lock for all synchronized instance block of code.

Can you please give me more details about synchronization context.

Your replies will be appreciated.

like image 821
Mohammed Amr Avatar asked Jul 26 '11 11:07

Mohammed Amr


2 Answers

The synchronized keyword provides serial access to the block of code (which could be an entire method) it introduces. Serialization of access is done by using an object as a mutex lock.

The three basic uses of synchronized are:

A. On a static method:

static synchronized void someStaticMethod() {
   // The Class object - ie "MyClass.class" - is the lock object for this block of code, which is the whole method
}

B. On an instance method:

synchronized void someInstanceMethod() {
   // The instance - ie "this" - is lock object for this block of code, which is the whole method
}

C. On an arbitrary block of code:

private Object lock = new Object();
void someMethod() {
    synchronized (lock) {
        // The specified object is the lock object for this block of code
    }
}

In all cases, only one thread at a time may enter the synchronized block.

In all cases, if the same lock object is used for multiple blocks, only one thread may enter any of the synchronised blocks. For example, if there are two - other simultaneous threads calling the methods will block until the first thread exits the method.

like image 160
Bohemian Avatar answered Oct 01 '22 11:10

Bohemian


Applying the synchronized keyword to a non-static method is shorthand for:

public void method() {
    synchronized(this) {
        // method
    }
}

If you apply synchronized to a static method, then it locks the class object (MyClass.class) whilst the method is called.

like image 32
Charles Goodwin Avatar answered Oct 01 '22 12:10

Charles Goodwin