Search code examples
javamultithreadingconcurrencyprimitivecritical-section

Why cannot I use primitive as mutex of syncronized section?


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 ?


Solution

  • 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.