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