What is a synchronization context in Java

You all know that the context of synchronization in Java, which they can be

  • in the copy.
  • in the java.lang.Class instance for the specific loaded class.
  • for this object

And I need to ask; When I write

Dimension d = new Dimension(); synchronized(d){ // critical atomic operation } 

synchronization of this object, equal to synchronization on the instance in practice.

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

Could you give me more detailed information on the context of synchronization.

Your answers will be appreciated.

+6
source share
2 answers

The synchronized provides sequential access to a block of code (which can be an entire method) that it enters. Serializing access is performed using the object as a lock mutex .

The three main uses of synchronized :

a. By the 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. According to the 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 can enter the synchronized block.

In all cases, if the same blocking object is used for several blocks, only one thread can enter any of the synchronized blocks. For example, if there are two other simultaneous threads that call methods, they will be blocked until the first thread exits this method.

+4
source

Applying the synchronized keyword to a non-stationary method is abbreviated for:

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

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

+1
source

Source: https://habr.com/ru/post/893588/


All Articles