Multithreading in OCPJP exam Multithreading in OCPJP exam multithreading multithreading

Multithreading in OCPJP exam


If you have a synchronized instance method like that, it synchronizes on the instance, i.e. every instance can access the method on its own. But x is static, so any instance of TestSeven can access it concurrently. If doThings() is static, it synchronizes on the class, so only one instance can access synchronized code at a given time.


Here is what will happen.

public static syncronized void doThings();

This will synchronize method at class level. Which means only one instance of class will be able to access the code at an instance of time, Which means there is no possibility of static variable x to be modified by other instances.

In other case,

public syncronized void doThings();

This means that doThings(); method is synchronized on current object. i.e. an instance of TestSeven, so multiple instances can access the method which in turn can change the static shared variable x which is not desirable.


Making the method static will make it available at class level and not at the instance level, so method behaviour will be same for all the objects/instances of this class like a static variable. So class will become thread safe because method behaviour is not instance specific