Search code examples
javastaticsynchronize

Would synchronising on class object block the entire class (and its members)


Would this block all access to Foo and its static members while the statements in the class is executing?

MyBlock:
synchronize(Foo.class)
{
    // ... do something 
}

In other words, while MyBlock is executing, no other thread would be able to call any static methods in Foo, right?

Ok, if this does not do it. Then how do I stop a class and its members from being accessed for a certain amount of time? Thanks


Solution

  • No. The use of the lock object itself, the Foo.class object in this case, is unaffected by synchronized blocks using it as a lock object.

    You can't stop classes from using being used, unless you put them behind something like a proxy that controls access, or make the methods themselves conditionally block execution internally, which doesn't really prevent access but simulates it.