• Register
First time here? Checkout the FAQ!
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 assignment writing service bandar bola best waikiki restaurants boiler business car car insurance quotes car insurance quotes car insurance quotes car lease deals car leasing uk chwilówka przez internet zapewne company convey convey law complaints convey law reviews convey law service conveylaw cosmetic dentist csr classics hack csr classics hack csr classics hack data data recovery maidenhead deals design development double glazing leeds electrician electrician manchester electricians emergency farm filmy bez limitu filmy online finlock finlock solutions general genral golf holidays spain graduate jobs in london graduate jobs london heap how to jump higher how to jump higher how to jump higher infrared sauna infrared sauna saunas inline skating java judi bola law law firm in leeds lease leasing led lights led bulbs leeds legal smoke life insurance quotes log london manchester mercedes lease deals mercedes leasing mezzanine movies museums and art nikogo szybka chwilówka none none none ny male revue outsource link building paid search agency performance car hire personal personal injury lawyer porcelain veneers ramię szybkie chwilówki recovery restaurant seo seo agencies seo company seo company london seo las vegas seo services services sky diamond seo solutions steel synchronization szybka chwilówka przykład szybka chwilówka żaden szybkie chwilówki lekko temp cover car insurance temp cover car insurance temp cover car insurance thread tymczasem chwilówki przez internet upvc windows manchester viagra kamagra videos vinyl flooring suppliers wait web development company window repairs london windows zobaczyć szybka chwilówka

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

0 votes

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

asked Jul 16, 2012 in Java/J2EE by anonymous

1 Answer

0 votes

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() {

		try {
			synchronized (BumpTest.class) { 
                        //or synchronized (Class.forname("BumpTest"))
		} 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. 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.

answered Jul 16, 2012 by sarada Hot Users (2,340 points)
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?
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?
There are several ways to synchronize access to a static variable.

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

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

Synchronize on some other static object.
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.