views:

47

answers:

2

Hi, I'm trying to test java.util.concurrent.ConcurrentLinkedQueue when accessed via multiple threads. Mentioned below is my Junit test using RepeatedTest to run in two concurrent threads. My questions is: is it correct to use RepeatedTest to test concurrency for example on ConcurrentLinkedQueue? The source code is mentioned below.

Thanks

import java.util.concurrent.ConcurrentLinkedQueue;
import junit.extensions.ActiveTestSuite;
import junit.extensions.RepeatedTest;
import junit.extensions.TestSetup;
import junit.framework.TestCase;

public class TestNonBlockingConcurrentQueue extends TestCase{

private static ConcurrentLinkedQueue clq;

public void testPut() throws Exception {
    int messageCounter = 0;
    for(;messageCounter <10000; messageCounter++){
        clq.offer(messageCounter);
    }
    assertEquals(clq.size(), messageCounter);
}

public void testGet() throws Exception {
    while(!clq.isEmpty()){
        clq.poll();
    }
    assertEquals("Size should be zero", clq.size(), 0);
}

public static junit.framework.Test suite( ) {
    ActiveTestSuite ats = new ActiveTestSuite();

    TestSetup setup = new TestSetup(ats) {
       protected void setUp() throws Exception {
            System.out.println("Creating ConcurrentLinkedQueue..");
            clq = new ConcurrentLinkedQueue();
        }
        protected void tearDown(  ) throws Exception {
            clq = null;
        }
    };
    ats.addTest(new RepeatedTest(new TestNonBlockingConcurrentQueue("testPut"), 2));
    ats.addTest(new RepeatedTest(new TestNonBlockingConcurrentQueue("testGet"), 2));
    return setup;

}

public TestNonBlockingConcurrentQueue(String testName){
    super(testName);
}
+1  A: 

JUnitPerf uses RepeatedTest to test concurrent code so it seems reasonable to use it to do the same thing with your test above, see:

http://www.clarkware.com/software/JUnitPerf.html

There are other methods for unit testing concurrent code, although none of them can really verify that your code is thread safe:

Also see: http://stackoverflow.com/questions/2035890/unit-testing-concurrent-code

Jon
A: 

You can never really run tests to check concurrency problems. The fact that no problem shows up on a particular test machine (on a given OS, with a certain number of cores or processors, or even just other processes running at the same time) doesn't mean that there isn't a problem.

Bruno
This is also true for non-concurrency problems. To quote 'Edsger W. Dijkstra': *Testing shows the presence, not the absence of bugs.*.
Willi
@Willi, absolutely! It's just that concurrency problems tend to be harder to detect, I think.
Bruno
Of course you can write tests for concurrency problems. You certainly can't write tests that are proof of the absence of bugs, but you can still test for the presence of specific bugs. These tests can be complicated to write however.
Jed Wesley-Smith