嵌套 'synchronize':如何重构此同步 Java 方法 - 它是否有意义?

Nested 'synchronize': How can this synchronized Java method be refactored - and could it make any sense like this?

我在做的一个项目中无意中发现了这个方法,立马想到哪里不对。我有一种感觉,这不可能是任何合适的惯用语。

但我不明白这样做的意图和含义。这可以重构吗?第二个同步是否有意义 - 第三个不是同步的 redundant/unnecessary?

我刚刚开始进入 java 中的高级 concurrent/threadsafe 编程 - 详细解释为什么这有意义或没有意义以及为什么非常感谢!

 @Override
    public synchronized void run() {
        synchronized (this.market) {
            synchronized (this.market.getWallet()) {
                this.handler.handleEvent(new WalletLecherEvent(this, market,
                        market.leechWallet()));
            }
        }
    }

提前致谢

编辑,以提供更多上下文:

public class WalletLeecherWorker extends Worker {
        private IAbstractMarketAPI market = null;

        private Thread thread = null;

        public WalletLeecherWorker(IEventHandler handler, IAbstractMarketAPI market) {
            super(handler);
            this.market = market;
        }

        public void startThread() {
            if (thread != null)
                return;

            thread = new Thread(this);
            thread.start();
        }

        public MARKETs getMarket() {
            return this.market.getName();
        }

        @Override
        public synchronized void run() {
            synchronized (this.market) {
                synchronized (this.market.getWallet()) {
                    this.handler.handleEvent(new WalletLecherEvent(this, market,
                            market.leechWallet()));
                }
            }
        }
    }

..和方法 market.getWallet():

@Override
public Wallet getWallet() {
    return this.wallet;
}

认为的目的是阻止所有线程获取钱包,从而错误地同步/弃用数据——只要这个线程运行();

代码获取了以下对象的锁:

  • this - 防止多个线程在同一个 WalletLeecherWorker 实例上调用 run()
  • this.market - 如果另一个线程获得了对它的锁定,则阻止 run() 继续,考虑到 market 实例可能是共享的,这是一个合理的假设
  • this.market.wallet - 与之前相同
其中

None 显然是不必要的,除了 run() 方法被同步。除了以下同步块所做的之外,它不提供任何保护。代码本身可能是因为使用了非常细粒度的锁定,这个特定代码需要锁定所有内容,而其他代码可能只锁定钱包或市场和钱包。

然而,这段代码很容易出错(甚至死锁)。如果以错误的顺序锁定对象,则可能会发生死锁。如您所见,它的可读性也不是很好。使用 startThread() 方法将 Thread 作为 class 的实例变量也是可疑的。代码可能没有破解,但肯定不是很漂亮。