繁体   English   中英

在Java中对非最终对象进行同步的正确方法

[英]The right way to synchronize on non-final object in Java

我正在尝试用锁保护对象。

我没有选择互斥锁,因为“ try..catch”的语法很丑陋。

浏览stackoverflow,我得出的结论是这是如何正确实现我的目标的方法:

class MyClass {
    private final Object lock = new Object();
    private Channel channel = null;

    public void setChannel() {
        synchronized (lock) {
            channel = new Channel();
            synchronized (channel) {
                // setup channel
            }
        }
    }

    public void unsetChannel() {
        synchronized (lock) {
            synchronized (channel) {
                channel.close();
            }
        channel = null;
        }
    }

    public boolean isSet() {
        synchronized (lock) {
            if (channel == null)
                return false;
            synchronized (channel) {
                return channel.isActive();
            }
        }
    }
}

但这看起来丑陋且难以阅读...

如何提高解决方案的可读性?

您可以简化锁定策略:

class MyClass {
    private final Object lock = new Object();
    private Channel channel = null;

    public void setChannel() {
        // other code can go here

        synchronized (lock) {
            channel = new Channel();
            // setup channel
        }

        // other code can go here
    }

    public void unsetChannel() {

        // other code can go here

        synchronized (lock) {
            channel.close();
            channel = null;
        }

        // other code can go here
    }

    public boolean isSet() {
        synchronized (lock) {
            if (channel == null) {
                return false;
            }
            return channel.isActive();
        }
    }
}

实际上, lock对象保护对通道变量的任何访问。

编辑以显示其他不与channel交互的代码可能位于锁之外的位置。

上外锁lock保护的一切。 您不需要第二把锁。 按住外部锁时,第二个线程永远无法到达该线程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM