Can a lock be acquired on a class

Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object..

Showing Answers 1 - 7 of 7 Answers

Aditya

  • Jul 26th, 2005
 

we can get lock on the class's Class object by using "static synchronize". This is the most exclusive lock.

  Was this answer useful?  Yes

Ajay Rout

  • Aug 27th, 2005
 

In class level the most exclusive lock can be achieved by synchronising the class's class object and declaring it static.

  Was this answer useful?  Yes

ramesh

  • Sep 9th, 2005
 

Classes can not be locked straightaway. 
One can not tell  
 
public synchronized class classname 
{ } 
 
But objects can be synchronized, also methods can be synchronized

  Was this answer useful?  Yes

As your might already know, any synchronisation needs an object (monitor) to acquire lock one. See below for the three different types on how to synchronise code.
public class A
{
  // A monitor object of sycnhronising piece of code.
   private Object mutex = new Object();

   // Type 1 - synchronise on current instance.
  // This method locks on its own instance object. No other thread can access this method or any other synchronised instance method on this instance (ex. method4) till the current thread completes processing in method1.
  public syncrhonized void method1()
  {
  }
 
  // Type 2 - synchronise on the java.lang.Class Object of the this type.
  // This method lock on the Class object created for this type. Every type has one class object created when the class file is loaded. No other thread can access this method or any other static method that is synchronsed in this class (ex. method5) till the current thread completes processing this method.
  pubic static synchronized void method2()
  {
  }

  // Type 3 - synchornise on any arbitary object.
  // Though the method is not synchronised, the piece of code inside the sync block is thread safe. No other thread can access this piece of code until the current thread completes processing. 
  public void method3()
  {
     // have some code here.
    synchronized (mutex)
    {
       // DO some thread safe stuff here.
     }
    // have some other code here.
  }

  public synchronized void method4(){}

  public static synchronized void method5() {}
}


You cannot say something like: pubic synchronized class A


Type 1 and Type 2 are commonly used. But they block all peer methods. The efficient way is to use Type3 where you can specify which object to use as monitor.

Hope that helps.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions