【问题标题】:How to avoid the race condition detected in the following code?如何避免在以下代码中检测到竞态条件?
【发布时间】:2016-08-05 11:51:43
【问题描述】:

考虑取自here的sn-p:

// event
public class Event { }
// An Event Listener
public interface EventListener {
        public void onEvent(Event e);
}

// inner class instances contain a hidden reference to the enclosing instance
public class ThisEscape {
    private final int num;

    public ThisEscape(EventSource source) {
        source.registerListener(new EventListener() {

            @Override
            public void onEvent(Event e) {
                doSomething(e);
            }
        });
        num = 42;
    }

    private void doSomething(Event e) {
        if (num != 42) {
            System.out.println("Race condition detected at " + new Date());
        }
    }
}
// event source

public class EventSource extends Thread {
    private final BlockingQueue<EventListener> listeners = 
                                new LinkedBlockingQueue<EventListener>();

    public void run() {
        while (true) {
            try {
                listeners.take().onEvent(null);
            } catch (InterruptedException e) {
                break;
            }
        }
    }

    public void registerListener(EventListener eventListener) {
        listeners.add(eventListener);
    }
}


// testing the conditions

public class ThisEscapeTest {
    public static void main(String[] args) {
        EventSource es = new EventSource();
        es.start();
        while (true) {
            new ThisEscape(es);
        }
    }
}

为了巩固,我们有 2 个线程

// Main Thread
// Event Source

在Event Source线程中,有一个BlockingQueue来存储EventListener。 在同一线程的run方法中,

使用 EventSource 线程不断从阻塞队列中取出对象,并对其进行处理。如果同一个线程试图从一个空队列中取出一个对象,那么同一个线程会被阻塞,直到 producing thread(主线程)将一个对象放入队列中。

由于这 2 个操作(如下)不是原子的,由于一些不幸的时间安排,所以在相同的 2 个操作之间,EventSource 很可能会发现 num != 2 & 因此比赛条件。

source.registerListener(new EventListener() {   // OPERATION 1      
    @Override
    public void onEvent(Event e) {
        doSomething(e);
    }
    });
    num = 42;                                       // OPERATION 2
}

既然建议并清楚地看到,内部类实例包含对封闭实例的隐藏引用。

虽然同一个线程(主线程)已经获得了锁,但非同步方法doSomething()仍然可以同时被另一个线程(在本例中为EventSource)访问,我看到即使同步上面的 2 个操作也不会避免竞争条件。我的理解正确吗? 我是说

 public ThisEscape(EventSource source) {
     synchronized(this){                // SYNCHRONISED
         source.registerListener(new EventListener() {
            @Override
            public void onEvent(Event e) {
                doSomething(e);
            }
         });
    num = 42;
    }
}

避免竞争条件的唯一方法是使doSomething() 方法也同步,除了同步两个操作?

第三,我看看这个字段是否是 final 的,它没有任何区别。比赛条件仍然存在。作者关于final字段的讨论点到底是什么(除了制作private final int num = 42)?

【问题讨论】:

  • 您是否有理由不简单地将分配num = 42 移动到注册侦听器上方?这就是“javaspecialist”想要告诉你的。
  • @meriton:谢谢,没错。我要求除此之外的解决方案。事实上,我想说的和问题的最后一行一样。
  • ...为什么你忽略了最佳实践? (如果有更好的解决方案,这种做法就不是最好的了,不是吗?)
  • “我如何解决因做'愚蠢的事情'而引起的问题”的答案通常是“停止做'愚蠢的事情'”。您认为通过在构造函数中发布this 可以获得什么好处?为什么你认为通过使用奇怪的东西而不是重新排列你的陈述更容易解决它?
  • @k5_:我是 Java 新手。做傻事。我就是这样学习的。

标签: java race-condition


【解决方案1】:

正如您已经意识到的那样,在构造函数中发布this 是一个非常糟糕的主意。

这是一个很好的解决方法;使用工厂方法。

public static ThisEscape newInstance(EventSource source){
   final ThisEscape instance = new ThisEscape();
   source.registerListener(new EventListener() {

        @Override
        public void onEvent(Event e) {
            instance.doSomething(e);
        }
    }
   return instance;
}

【讨论】:

    【解决方案2】:

    通过在初始化num 字段之前调用registerListener(),您显然将自己暴露在num 设置之前被访问的风险。更重要的是,num 是从不同的线程访问的,因此无法保证一旦设置,就会读取正确的值。

    可能的解决方案是预先初始化num

    public static class ThisEscape {
        private final int num = 42;
    
        public ThisEscape(EventSource source) {
            source.registerListener(e -> doSomething(e));
        }
        //...
    }
    

    或者让它 volatile 并在调用 registerListener() 之前设置它

    public static class ThisEscape {
        private volatile int num;
    
        public ThisEscape(EventSource source) {
            num = 42;
            source.registerListener(e -> doSomething(e));
        }
        //...
    }
    

    编辑:感谢@AndyTurner 和@ShirgillFarhanAnsari 指出错误。

    【讨论】:

    • 简单地颠倒陈述并不能保证消除问题。如果您在构造函数完成后注册侦听器,则只能保证分配发生在调用 doSomething 之前,因为最终字段分配的发生之前的行为。
    • 第一个解决方案很好。第二个并不是我所知道的,它并不能保证在另一个之前的指令/操作保证在另一个之前执行。
    【解决方案3】:

    这与转义this 指针无关。 num 在外部类中的事实并没有改变并行活动需要同步的事实。

    如您所述,有 2 个操作:

    1. registerListener
    2. 设置num = 42

    现在onEvent 回调可以在registerListener 返回后不久甚至在它返回之前调用,因为它是异步的。在任何情况下,之前或之后num = 42。它需要同步或正确排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多