我现在使用的是Java并发。
我不知道如何写负面的场景测试。
我需要一种方法来制造死锁,我需要一种方法来认识到,如果不使用同步,我可能会遇到像不一致这样的问题。
如果忽略了synch,那么编写压力测试代码的最佳方式是什么?
任何代码示例都是非常有价值的。
提前感谢大家!
发布于 2010-02-26 23:08:50
下面的代码几乎肯定会创建死锁,并演示了典型的死锁场景,即两个不同的线程以不一致的顺序获取锁。
public class Main {
private final Object lockA = new Object();
private final Object lockB = new Object();
public static void main(String[] args) {
new Main();
}
public Main() {
new Thread(new Runnable() {
public void run() {
a();
sleep(3000L); // Add a delay here to increase chance of deadlock.
b();
}
}, "Thread-A").start();
new Thread(new Runnable() {
public void run() {
// Note: Second thread acquires locks in the reverse order of the first!
b();
sleep(3000L); // Add a delay here to increase chance of deadlock.
a();
}
}, "Thread-A").start();
}
private void a() {
log("Trying to acquire lock A.");
synchronized(lockA) {
log("Acquired lock A.");
}
}
private void b() {
log("Trying to acquire lock B.");
synchronized(lockB) {
log("Acquired lock B.");
}
}
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch(InterruptedException ex) {
}
}
private void log(String msg) {
System.err.println(String.format("Thread: %s, Message: %s",
Thread.currentThread().getName(), msg));
}
}
下面的代码演示了由于两个线程之间缺乏并发控制而可能产生不一致结果的情况。
public class Main {
// Non-volatile integer "result".
private int i;
public static void main(String[] args) {
new Main();
}
public Main() {
Thread t1 = new Thread(new Runnable() {
public void run() {
countUp();
}
}, "Thread-1");
Thread t2 = new Thread(new Runnable() {
public void run() {
countDown();
}
}, "Thread-2");
t1.start();
t2.start();
// Wait for two threads to complete.
t1.join();
t2.join();
// Print out result. With correct concurrency control we expect the result to
// be 0. A non-zero result indicates incorrect use of concurrency. Also note
// that the result may vary between runs because of this.
System.err.println("i: " + i);
}
private void countUp() {
// Increment instance variable i 1000,000 times. The variable is not marked
// as volatile, nor is it accessed within a synchronized block and hence
// there is no guarantee that the value of i will be reconciled back to main
// memory following the increment.
for (int j=0; j<1000000; ++j) {
++i;
}
}
private void countDown() {
// Decrement instance variable i 1000,000 times. Same consistency problems
// as mentioned above.
for (int j=0; j<1000000; ++j) {
--i;
}
}
}
发布于 2013-03-14 17:39:02
在上面的死锁例子中。死锁的时间是3秒。之后,lockA和lockB被释放并被线程2和线程1占用
https://stackoverflow.com/questions/2342315
复制相似问题