[英]how can i test the synchronization of my blocking Queue implementation
我刚刚用信号量编写了一个简单的阻塞队列,我将测试它的同步。
我已经在大量插入和从队列中删除的线程上测试了我的实现稳定性,
我想得到一些关于如何以更正确的方式测试它的想法\\测试的帮助。
public class BBQ<T> {
private ArrayList<T> tasks;
private Semaphore mutex;
private Semaphore full;
private Semaphore zero;
public BBQ(int numofWorkers){
tasks = new ArrayList<T>();
mutex = new Semaphore(1, true);
full = new Semaphore(numofWorkers, true);
zero = new Semaphore(0, true);
}
public boolean add(T item) {
boolean ans = false;
try {
zero.acquire();
mutex.acquire();
ans = tasks.add(item);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally{
mutex.release();
full.release();
}
return ans;
}
public boolean remove() {
boolean ans = false;
try {
full.acquire();
mutex.acquire();
if (tasks.remove(0) == null) {
ans = false;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
finally{
mutex.release();
zero.release();
}
return ans;
}
public int size() {
return tasks.size();
}
public String toString() {
return tasks.toString();
}
您的size
和toString
不是线程安全的。 没有万无一失的方法来测试线程安全性,而编写简单易懂且易于验证的代码则要好得多。
可以说,进行简单测试并没有什么坏处,因为这可能会显示错误。 (没有错误并不意味着它是线程安全的)
我会使用ExecutorService尽快添加和删除条目,看看它是否进入错误状态。 特别是每次都会调用toString()
,因为我很确定这将失败,这是您应该能够展示的东西。
我会运行3种类型的测试来测试你的阻塞代码:
我想得到一些关于如何以更正确的方式测试它的想法\\测试的帮助。
您可以使用jcstress框架。 一些Oracle
工程师使用它进行内部测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.