Implicit synchronization in java?

when i have a method like

public void unsynchronizedMethod(){
  callSynchronizedMethod();
  //dosomestuff after this line
}

Does this mean that all content after calling the SynchronizedMethod () method in the unsynchronizedMethod () method is implicitly synchronized?

+3
source share
4 answers

Synchronization is determined in a simple way:

  • For the method synchronized: when executing this method
  • For a block synchronized: when executing this block

Here are the relevant excerpts from the Java Language Specification 3rd Edition:

JLS 14.19 Statement synchronized

A synchronized:

  • gets a mutual exclusion lock on behalf of an executable thread,
  • executes a block
  • then releases the lock.

, .

synchronized synchronized, (§JLS 8.4.3.6. this ( ) Class , ( a static, this static).

, , :

public void unsynchronizedMethod(){
  callSynchronizedMethod();

  doSomeUnsynchronizedStuff(); // no "implicit synchronization" here
}

, : . .

.

  • Java 2nd Edition, 67:

+3

. callSynchronizedMethod().

+6

, .

, .

callSynchronizedMethod() , .

0

, . . , , .

. 0.

class example extends Thread{
   //Global value updated by the example threads
   public static volatile int value= 0;
    public void run(){
    while(true)//run forever
       unsynchMethod();

   }
   public void unsynchMethod(){
     synchronizedMethod();
    //Count value up and then back down to 0
    for(int i =0; i < 20000;++i)
       value++;//reads increments and updates value (3 steps)
    for(int i = 0; i < 20000;++i)
       value--;//reads decrements and updates value (3 steps)
      //Print value 
      System.out.println(value);
   }
   //Classlevel synchronized function
   public static synchronized void synchronizedMethod(){
      //not important
   }
   public static void main(String... args){
    example a = new example();
    example b = new example();
    a.start();
    b.start();
   }

}

, 0, :

4463
6539
-313
-2401
-3012
...
0

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


All Articles