开发者

Making class object as synchronized variable

    private static class开发者_JS百科 RunningMutex {}
    private static class ObserveMutex {}

    private static volatile RunningMutex runningMutex = new ImportActionRunningMutex();
    private static volatile ObserveMutex observeMutex = new ImportActionObserveMutex();



    synchronized (observeMutex) {......}  .... (1)
    synchronized (runningMutex) {......}  .....(2)

Is it a good practice to have code something like above ? I am currently refactoring a big code which is not working properly and I found out these lines. I would like to know if there is some alternative to the above code.


It's not an uncommon pattern when you want to isolate different locks from eachother in the same class, or when you want to share the same lock across different classes. It's not strictly necessary to create specified classes for each different lock (could just use different Object instances), but it helps a lot when you're analyzing thread dumps as it will be clear which thread owns which monitor.

The danger is that you can create dead-lock situations unless you're careful (thread X locks monitor A, thread Y locks monitor B, thread X tries to lock monitor B, thread Y tries to lock monitor A).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜