Distinguish Between Synchronized Statics & Synchronized Instance Methods

Distinguish Between Synchronized Statics & Synchronized Instance Methods

When you invoke a synchronized static method, you obtain the lock associated with the Class object in whose class the method is defined.

When you apply synchronized to instance methods and object references, you obtain the lock for the object on which the method was invoked.

The following code is not thread safe:

 Class Foo implements Runnable{   public void printX()   {	while(true)        {	    System.out.println(“X”);        }   }   public static void printY()   {	while(true)        {	    System.out.println(“Y”);        }   }   public void run()   {      printX();   }}Class Test{   public static void main(String args[])   {	Foo f = new Foo();	Thread t = new Thread(f);	t.start();	f.printY();   }}

The methods ‘printX()’ & ‘printY()’ attempt to execute concurrently, because they are invoked on separate threads.Because they obtain two different locks, execution interleaves between them.

When both methods share a common resource, you need to protect it to avoid a conflict. The first way is simply to synchronize on the common resource.A second way is to synchronize on a special instance variable; i.e. declaring a local instance for the sole purpose of synchronizing on it. Here’s an example:

 Class One implements Runnable{   private byte[] lock = new byte[0];   public void printX()   {	synchronized(lock)        {	    // The code to protect.        }   }   public static void printY()   {	synchronized(lock)        {	    // The code to protect.        }   }}

A zero element array is used because such an array is cheaper to create than any other object. Why? Because it doesn’t require a constructor call like the creation of Object does. Thus, it executes faster.

See also  5 Tips for Choosing the Right Medical Software for Your Practice

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist