0

I noticed interesting(surprising for me) behaviour:

public void m(){
        int primitive=1;
        synchronized (primitive) {

        }
    }

this code generates following:

int is not a valid type's argument for the synchronized statement

Can you explain why ?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • possible duplicate of [What primitive is used to implement the synchronized keyword?](http://stackoverflow.com/questions/15684530/what-primitive-is-used-to-implement-the-synchronized-keyword) – hyde Jul 01 '14 at 07:27
  • because it takes an object. – Scary Wombat Jul 01 '14 at 07:27
  • To be specific how that duplicate answers the question: `monitorenter` takes an object. Primitives are not objects. JVM has no way to synchronize on them. – hyde Jul 01 '14 at 07:28
  • That duplicate links to a very good page: http://www.javaworld.com/article/2076971/java-concurrency/how-the-java-virtual-machine-performs-thread-synchronization.html – sina72 Jul 01 '14 at 07:30
  • @hyde it is absolutely another question – gstackoverflow Jul 01 '14 at 07:38
  • @Scary Wombat but I could not watch signature of input arguments – gstackoverflow Jul 01 '14 at 07:46
  • see http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html – Scary Wombat Jul 01 '14 at 07:52
  • quote: Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock: – Scary Wombat Jul 01 '14 at 07:52
  • It might not be clear to some readers, so I'll augment above quote of @ScaryWombat by adding that synchronized methods also must have an object to synchronize on (`this` or the class object), it's just implicitly specified by method type (instance or static method). – hyde Jul 01 '14 at 09:33

1 Answers1

7

A primitive is just a bare value, nothing else. This is the whole point of a primitive, it is as simple as possible. Adding a lock is an overhead, i.e. it add 4 bytes, and the Object's entire header can be 16 bytes.

Only Objects have support for methods and synchronized.

The reason it matters is that a byte uses one byte, but a Byte which can be locked uses 16 to 24 bytes. If you have a buffer with millions of these, having support for a lock seems like a waste if you don't need it.

BTW, you should never lock on a local or mutable variable unless you like confusion.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130