开发者

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, t开发者_如何学运维hen 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜