0 votes
in Java/J2EE by

Can we synchronize static method/variable in a Java class?

   

1 Answer

0 votes
by Hot Users (2.3k points)

Yes, you can do it.

A synchronized method or block works on a given monitor. Synchronized non-static methods all synchronize on the Java instance of a class. Each instance has a lock monitor. For the case of static methods, what object does static synchronized methods use for locking? The static synchronized statements obtain a lock on the Class object. The following example show you few ways to access the class object:

class MyClass {

 ....

    public static void main(String[] args) {
        //you can access class object through an instance of that class
        MyClass objectinstance = new MyClass();
        java.lang.Class myclass1 = objectinstance.getClass();

        //non-instance ways
        java.lang.Class myclass2 = Myclass.class;
	java.lang.Class myclass3 = Class.forName("MyClass");
    }

}

The JVM creates a Class object when the class is loaded (When it is used for the first time). Once a class is loaded into a JVM, the same class will not be loaded again. The JVM creates one instance of Class for each class that is loaded, The Class instances are Objects and can be synchronized via static synchronized methods.

For example

class MyClass  {
  ...
  public synchronized static someMethod() {
    ...
  }
  ...
}

It is the equivalent to the following static synchronized block:

synchronized ( MyClass.class ) {
...
}

In some situatios, you need to protect access static variables, the locking an object instance does not automatically protect access to static variables, because there may have more than one instances and all of them use the same static variables. You have to obtain a lock on the Class vs an instance of the class. A static synchronized block can be use to protect access to static varibales, a lock on a static method has no effect on any instances of that class (see the Java Language Specification). For example,

class BumpTest {

	int count;
	static int classCount;
	void synchronized bump() {
		count++;

		try {
			synchronized (BumpTest.class) { 
                        //or synchronized (Class.forname("BumpTest"))
				classCount++;
			}
		} catch (ClassNotFoundException e) {
	}
				...
}

Static variables, like static methods, are not inherited, but are accessible from within the body of the class definition and through an explicit reference to the defining class's name. Adding a new static synchronized method in a subclass cannot protect other threads to access static variables defined in its superclass nor should you use synchronized(this.getClass()) which locks the actual Class might be the subclass. An explicit block synchronization with "none-instance way to get Class" is the preferred way.

 

8.4.3.6 synchronized Methods

A synchronized method acquires a monitor (??17.1) before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

by
I know that using the synchronize keyword before a method brings synchronization to that object.
That is, 2 threads running the same instance of the object will be synchronized.
However, since the synchronization is at the object level, 2 threads running different instances of the object will not be synchronized. So, if we have a static variable in a java class that is called by the method, we would like it to be synchronized across instances of the class.
The two instances are running in 2 different threads.
Can we achieve synchronization in the following way?
Code:
public class Test { private static int count = 0; private static final Object lock= new Object(); public synchronized void foo() { synchronized(lock) { count++; } } }
Is it true that since we have defined an object 'lock' that is static and we are using the keyword synchronized for that lock, the static varibale count is now synchronized across instances of class Test?
by Hot Users (2.3k points)
There are several ways to synchronize access to a static variable.

Use a synchronized static method. This synchronizes on the class object.
Code:
public class Test { private static int count = 0; public static synchronized void incrementCount() { count++; } }

Explicitly synchronize on the class object.
Code:
public class Test { private static int count = 0; public void incrementCount() { synchronized (Test.class) { count++; } } }

Synchronize on some other static object.
Code:
public class Test { private static int count = 0; private static final Object countLock = new Object(); public void incrementCount() { synchronized (countLock) { count++; } } }

Method 3 is the best in many cases because the lock object is not exposed outside of your class.
Welcome to Find4Answers.com

Where you can Ask Questions, Find Answers Or Receive Answers from other members of the community And Share in Social networking sites like facebook, linkedin, twitter.
3cx phone system bandar bola benches boiler business bóg chwilówka przez internet car car lease deals car leasing uk chwilówka przez internet zapewne company convey convey law complaints convey law reviews convey law service conveylaw cornwall cosmetic dentist data data recovery maidenhead data recovery nottingham deals deepika padukone deepika padukone hot design development dot net programming dzieje szybkie chwilówki electrician electrician manchester electricians emergency farm filmy bez limitu filmy bez limitów filmy online finlock finlock solutions general genral graduate jobs in london graduate jobs london gutters hard drive recovery heap http: www.seo-assist.in infrared sauna infrared sauna saunas inline skating installation jabong coupon java judi bola laptop recycling law law firm in leeds lease leasing led lights led bulbs leeds life insurance quotes log london manchester movies museums and art myntra coupon nikogo szybka chwilówka outsource link building personal porcelain veneers ramię szybkie chwilówki recovery seo seo agencies seo company seo company london seo services services solutions stair lifts steel synchronization szybka chwilówka przykład szybka chwilówka żaden szybkie chwilówki lekko thread tunnel lighting tymczasem chwilówki przez internet upvc windows manchester viagra kamagra videos vinyl flooring suppliers wait web design services london web development company window repairs london windows yebhi coupon zobaczyć szybka chwilówka
...