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

StackOverflow https://stackoverflow.com/questions/20638170

  •  18-09-2022
  •  | 
  •  

質問

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

役に立ちましたか?

解決

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.

他のヒント

If you want to lock on static members, you can define a dummy static member to wich you can lock, and every time you want to access the static members, you'll just check if that dummy member is locked.

class Foo{
     public static Integer dummyLock;
....
}

afterwhich you can: MyBlock:

synchronize(Foo.dummyLock)
{
    // ... access static members here
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top