我正在做一些作为大学任务的一部分,所要求的部分内容是模拟线程故障。对于上下文,我正在使用Java SE的执行器服务模拟Java中的线程故障
我环顾了一下SO和Google,但一直没有找到具体或具体的东西来做这样的事情。
有没有人知道或有任何有关如何处理信息或指导的好消息?
我正在做一些作为大学任务的一部分,所要求的部分内容是模拟线程故障。对于上下文,我正在使用Java SE的执行器服务模拟Java中的线程故障
我环顾了一下SO和Google,但一直没有找到具体或具体的东西来做这样的事情。
有没有人知道或有任何有关如何处理信息或指导的好消息?
如果你想测试线程如何“失败”时,他们遇到异常,你可以实现一个Runnable
,你可以命令失败:
public class FailingRunnable implements Runnable {
private volatile boolean doFail = false;
@Override
public void run() {
while(!doFail && ! Thread.interrupted())
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
throw new RuntimeException("failed");
}
public void failOnNextOccasion() {
doFail = true;
}
}
你必须保持在可运行的引用添加之后给执行者,然后在任何时候调用可运行的方法failOnNextOccasion()
。就像这样:
ExecutorService execSrv = Executors.newFixedThreadPool(2);
FailingRunnable one = new FailingRunnable();
FailingRunnable two = new FailingRunnable();
execSrv.submit(one);
execSrv.submit(two);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
one.failOnNextOccasion();
two.failOnNextOccasion();
有点复杂的线程有不那么明显的错误失败:
public class Test {
static class FailerThread implements Runnable {
final Object[] objects;
final Random random;
final int number;
public FailerThread(final Object[] objects, final int number) {
this.objects = objects;
this.random = new Random();
this.number = number;
}
@Override
public void run() {
final boolean isWriter = number % 2 == 0;
int index = random.nextInt(objects.length);
try {
while (Thread.interrupted() == false) {
synchronized (objects) {
if (isWriter) {
while (objects[index] == null) {
System.out.println(number + ": Index " + index + " is null, waiting...");
objects.wait();
}
for (int copyIndex = 0; copyIndex < objects.length; ++copyIndex) {
if (objects[copyIndex] == null) {
objects[copyIndex] = this.objects[index];
}
}
objects.notifyAll();
} else {
objects[index] = null;
}
}
++index;
if (index >= objects.length) {
index = 0;
}
}
} catch (InterruptedException e) {
}
}
}
public static void main(String[] args) throws InterruptedException {
final Object[] objects = new Object[10];
for (int i = 0; i < objects.length; ++i) {
objects[i] = new Object();
}
final int NUM_THREADS = 32;
final ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; ++i) {
executor.execute(new FailerThread(objects, i));
}
}
}
应该立即失败,但是这样做的原因是一切,但微不足道。
您正在检查InterruptedException中的中断标志有一个空的catch-block。谁会设置中断标志? – mwhs
_thread failures_是什么意思? –
你的意思是你的'Runnable'或'Callable'应该在执行动作时抛出一个异常? –
@SotiriosDelimanolis我的歉意,应该更清楚。我如何解释这个问题是我需要以某种方式在线程池中完成一项任务,以便有随机失败的机会。 为了进一步澄清,这是我得到的 “模拟线程故障并实现适当的监视和恢复机制。” 此外,我不是在找人来做我的工作,只是想法或信息。 – Eogcloud