Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Advanced
Dec 13, 2002

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.
Asaf Levy
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date