javasynchronized

Why is the synchronize keyword restricted to non primitive fields only?


In java there is a synchronize keyword that is used to avoid multiple thread access to a method or some block of code at some point.

My question is why can’t the synchronize keyword be used with primitive variables? I know that java does not permit this. But what is the logic as to why this isn’t permitted since all variables in java are Objects including primitive types like int,float etc.

e.g.

int a=1;
synchronized(a){}//why is this forbidden 

Solution

  • Variable in itself does not stand on its own. It needs a class to have some context. That's why the lock is on the class or the object and not on the variable.