Static members need special synchronization blocks?

I have a class that looks something like this:

public class Test {

private static final Object someObject = new Object();

public void doSomething()
{
    synchronized (someObject) {
        System.out.println(someObject.toString());
    }
}

}

Is it possible to consider the object synchronized or a problem has occurred, since it is a static member?

Edit: note that in this case, access to doSomething () and other objects should flow.

+3
source share
4 answers

Using a static object as a monitor object, only one thread, using any instance of the Test class, can fall into the synchronization block. If the monitor object was not a static object, other threads containing different instances of the Test class could fall into the synchronization block.

+7
source

someObject () all Test. , doSomething() Test, . , someObject, .

someObject . , , "private lock object", 70 Java.

+4

:

public class Test {
  public void doSomething() {
    synchronized (Test.class) {
      // something
    }
  }
}

what the synchronized static method actually does. Of course, if you want more than one lock like this, you need to declare them as static fields, as in your example.

+1
source

What happens if the Test class is loaded using different class loaders?

0
source

All Articles