[concurrency-interest] why bytecode difference between synchronized block and method

Peter Veentjer alarmnummer at gmail.com
Sun Nov 19 07:45:06 EST 2006


Why is there a difference in the bytecode between a synchronized block
(as first statement of a method) and a synchronized method? I don't
understand why there should be any difference but if I look at the
bytecode of the following example, there is.

example:
import java.util.*;

public class DifferenceMain{

    private List list = new LinkedList();

    public void foo(){
		synchronized(this){
			if(list.size()==0)
				list.add("foo");
		}
	}

    public synchronized void bar(){
		if(list.size()==0)
			list.add("bar");
    }

    public static void main(String s){
    }
}


bytecode:
Compiled from "DifferenceMain.java"
public class DifferenceMain extends java.lang.Object{
public DifferenceMain();
  Code:
   0:	aload_0
   1:	invokespecial	#1; //Method java/lang/Object."<init>":()V
   4:	aload_0
   5:	new	#2; //class java/util/LinkedList
   8:	dup
   9:	invokespecial	#3; //Method java/util/LinkedList."<init>":()V
   12:	putfield	#4; //Field list:Ljava/util/List;
   15:	return

public void foo();
  Code:
   0:	aload_0
   1:	dup
   2:	astore_1
   3:	monitorenter
   4:	aload_0
   5:	getfield	#4; //Field list:Ljava/util/List;
   8:	invokeinterface	#5,  1; //InterfaceMethod java/util/List.size:()I
   13:	ifne	28
   16:	aload_0
   17:	getfield	#4; //Field list:Ljava/util/List;
   20:	ldc	#6; //String foo
   22:	invokeinterface	#7,  2; //InterfaceMethod
java/util/List.add:(Ljava/lang/Object;)Z
   27:	pop
   28:	aload_1
   29:	monitorexit
   30:	goto	38
   33:	astore_2
   34:	aload_1
   35:	monitorexit
   36:	aload_2
   37:	athrow
   38:	return
  Exception table:
   from   to  target type
     4    30    33   any
    33    36    33   any

public synchronized void bar();
  Code:
   0:	aload_0
   1:	getfield	#4; //Field list:Ljava/util/List;
   4:	invokeinterface	#5,  1; //InterfaceMethod java/util/List.size:()I
   9:	ifne	24
   12:	aload_0
   13:	getfield	#4; //Field list:Ljava/util/List;
   16:	ldc	#8; //String bar
   18:	invokeinterface	#7,  2; //InterfaceMethod
java/util/List.add:(Ljava/lang/Object;)Z
   23:	pop
   24:	return

public static void main(java.lang.String);
  Code:
   0:	return

}


More information about the Concurrency-interest mailing list