开发者

Setting local field from timer

开发者 https://www.devze.com 2023-04-08 15:46 出处:网络
I have the following problem in my unit test. The class with tests: class TestClass { boolean stopTest = false;

I have the following problem in my unit test. The class with tests:

class TestClass {
    boolean stopTest = false;

    @Test
    public void test() {
        // do something
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                stopTest = true;
            }
        }, 1200);
        while(!stopTest) {
        }
        timer.cancel();
        // do assert
    }
}

This test works right only in debug with breakpoint on while operator, but if I run test not in debug or without breakpoint, he works infinitely. I tried to change stopTest to class with boolean field, also a tried to work th开发者_运维问答rough get and set methods in this class. What I do wrong?


You need to use the volatile modifier due to concurrency, otherwise stopTest cannot be reliably updated and read. For more information, see JLS §8.3.1.4 - volatile Fields.

volatile boolean stopTest = false;


You should declare stopTest to be volatile.

See also:

  • volatile vs atomicboolean
  • synchronized methods
  • tutorial on concurrency


@JRL and @mrkhrts are right. But I would like to suggest something else.

You really do not need timer here. You just want to run some code in separat thread and make your main thread to wait until this asynchronous task is done. Do it using simple thread and join() method:

@Test
public void test() {
    // do something
    Thread t = new Thread() {
        public void run() {
            try {Thread.sleep(1200)} catch(InterruptedException e) {}
            // do what you want here
        }
    }
    t.start();

    t.join(); // this line will be bloked until the async task is done.
}
0

精彩评论

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

关注公众号