如何编写测试并发不变量的单元测试

Lux*_*ode 9 java unit-testing

关于这个问题还有其他问题,但我正在试图如何处理这样的单元测试:

 public class Semaphore extends Lock {
        private AtomicInteger semaphore = new AtomicInteger(0);
        public synchronized boolean available() {
                return semaphore.intValue() == 0;
        }
        public synchronized void acquire() {
            semaphore.incrementAndGet();

        }
        public synchronized void release() {
            semaphore.decrementAndGet();
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我的朴素锁定机制(仅用于学习目的).我该如何测试这个线程的安全性?我知道在单元测试并发代码方面没有任何保证,但是我怎样才能编写单元测试ATTEMPTS来测试这种锁定机制中固有的明显不变量?

Lux*_*ode 6

我想自从我做了一些研究后,我会回答我自己的问题.有一个很棒的框架叫做MultithreadedTC.它允许您设置如下测试:

public class SafeSemaphoreTest extends MultithreadedTestCase {

    private SafeSemaphore semaphore;
    AtomicInteger ai = new AtomicInteger(0);

    @Override
    public void initialize() {
        semaphore = new SafeSemaphore();
    }


    public void thread1() throws InterruptedException {

        assertTick(0);

        semaphore.acquire();
        waitForTick(2);
        assertTick(2);

        semaphore.acquire();
        assertEquals(semaphore.getValue(), 2);
        assertEquals(semaphore.getValue()==3, false);
        semaphore.release();
        semaphore.release();

    }

    public void thread2() throws InterruptedException {
        waitForTick(1);
        assertTick(1);
        assertEquals(semaphore.available(), false);
        waitForTick(3);
        assertTick(3);
        assertEquals(semaphore.available(), true);

    }

}
Run Code Online (Sandbox Code Playgroud)

其中waitForTick(int)调用生成当前Thread块直到达到tick.为了更好的JUnit集成,甚至还有一些开发使它更现代化:http: //janvanbesien.blogspot.com/2009/06/modernizing-multithreadedtc-junit-4.html