Jvm differences between synchronized and unsynchronized methods

I have the following class:

public class SeqGenerator {

    int last = 0;
    volatile int lastVolatile = 0;

    public int getNext() {
        return last++;
    }

    public synchronized int getNextSync() {
        return last++;
    }

    public int getNextVolatile() {
        return lastVolatile++;
    }

    public void caller() {
        int i1 = getNext();
        int i2 = getNextSync();
        int i3 = getNextVolatile();
    }

}

When I look at the parsed code, I see no difference between the representation of the three methods getNext(), getNextSync()and getNextVolatile().

public int getNext();
  Code:
   0:   aload_0
   1:   dup
   2:   getfield    #2; //Field last:I
   5:   dup_x1
   6:   iconst_1
   7:   iadd
   8:   putfield    #2; //Field last:I
   11:  ireturn

public synchronized int getNextSync();
  Code:
   0:   aload_0
   1:   dup
   2:   getfield    #2; //Field last:I
   5:   dup_x1
   6:   iconst_1
   7:   iadd
   8:   putfield    #2; //Field last:I
   11:  ireturn

public int getNextVolatile();
  Code:
   0:   aload_0
   1:   dup
   2:   getfield    #3; //Field lastVolatile:I
   5:   dup_x1
   6:   iconst_1
   7:   iadd
   8:   putfield    #3; //Field lastVolatile:I
   11:  ireturn

public void caller();
  Code:
   0:   aload_0
   1:   invokevirtual   #4; //Method getNext:()I
   4:   istore_1
   5:   aload_0
   6:   invokevirtual   #5; //Method getNextSync:()I
   9:   istore_2
   10:  aload_0
   11:  invokevirtual   #6; //Method getNextVolatile:()I
   14:  istore_3
   15:  return

How can the JMV distinguish between these methods?

The generated code is the same of these methods as well as their callers. How does the JVM synchronize?

+5
source share
2 answers

The keyword synchronizedapplied to a method simply sets a flag ACC_SYNCHRONIZEDin the definition of this method, as defined in the JVM specification § 4.6 Methods . It will not be visible in the actual bytecode of the method.

JLS § 8.4.3.6 synchronized synchronized, ( ): , - .class.

volatile: ACC_VOLATILE (JVM § 4.5 ). , , -, .

, threadsafe, x++ x !

+6

:

public int getNext();
   bytecodes follow...

public synchronized int getNextSync();
   bytecodes follow...

, volatile , - JVM, . javap, :

int last;

volatile int lastVolatile;

/ - JIT, , .

+4

All Articles