在本地测试并发性

时间:2012-05-02 10:21:28

标签: java testing concurrency

出现了一个问题,我们无法确定这个问题。它看起来像是一个共享单例bean的并发问题,但这只是假设。

我需要一种在本地重新创建此错误的方法。只有当两个线程在同一千分之一秒内一起处理时才会浮出水面。我想知道有没有办法在本地进行测试,而无需在调试模式下进行测试。

我们的过程很简单。

它从主题过程中获取对象并丰富,然后将要发布的新对象发送到主题。我们有两个监听线程。

Tech used

  • IDE eclipse
  • ldap主题
  • Code Java / Spring

1 个答案:

答案 0 :(得分:0)

细节太少无法给出准确答案。我会重构代码,所以所有的同步代码都与业务逻辑分开。然后,在测试期间,您可以使用调用yeld()方法的代码替换业务逻辑,并使用volatile / atomic变量来检查此时代码是否存在预期的线程数。然后使用任何并发测试框架(我喜欢multithreadedtc)。下面你可以找到piority队列实现我用来测试我的算法,它应该在队列上进行并发操作

class YeldingHeap implements PriorityQueue<Integer> {

private AtomicInteger concurrentReads = new AtomicInteger();
private AtomicInteger concurrentWrites = new AtomicInteger();

@Override
public int size() {
    read();
    return 0;
}

@Override
public void insert(Integer element) {
    write();
}

@Override
public Integer popMax() {
    write();
    return null;
}

private void write() {
    int writes = concurrentWrites.incrementAndGet();
    int reads = concurrentReads.incrementAndGet();
    assertEquals(writes, 1, "more than 1 thread is writing");
    assertEquals(reads, 1, "other thread is reading while this thread is writing");
    Thread.yield();
    writes = concurrentWrites.decrementAndGet();
    reads = concurrentReads.decrementAndGet();
    assertEquals(writes, 0, "more than 1 thread is writing");
    assertEquals(reads, 0, "other thread is reading while this thread is writing");
}

private void read() {
    concurrentReads.incrementAndGet();
    int writes = concurrentWrites.get();
    assertEquals(writes, 0, "other thread is writing while this thread is reading");
    Thread.yield();
    writes = concurrentWrites.get();
    assertEquals(writes, 0, "other thread is writing while this thread is reading");
    concurrentReads.decrementAndGet();
}

}