我想模拟一个我们在生产环境中遇到的挂起的线程。应用程序是一个web服务,并为新请求创建不同的线程。错误是所有的线程都依赖于一个同步的方法,而这种依赖在补丁中已经被删除了。如何在开发环境中模拟executor框架的挂起线程?
在Dev中,一切都很好,我如何才能确保一些线程挂起同步方法,就像生产一样?
package com.priority;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class StackOverFlow {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
executorService.submit(new Task());
}
executorService.shutdown();
}
}
class Task implements Runnable {
synchronized void syncMethod() {
System.out.println("This is the sync method causing issues");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
syncMethod();
}
}发布于 2018-04-13 17:47:44
让我们假设同步的资源(synchronized void syncMethod())在其他类中,以便executorservice外部的线程可以访问它。这种重构是重建饥饿场景所必需的。
创建几个贪婪的线程,这些线程会在随机时间内(比普通线程多)占用同步的资源。这类线程的数量可能取决于您的测试场景。
在您的executor服务之前触发贪婪的线程,以便它们获取资源。
现在,您可以测试实际线程在资源稀缺的情况下如何响应,还可以定义一个策略,以便在资源使用不均衡的情况下管理资源。
发布于 2018-04-13 17:56:56
如果没有显式object,synchronized将在this上执行,因此您发布的代码不会同步。
您应该为这些任务提供相同的监视器锁:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class StackOverFlow {
public static void main(String[] args) {
Object monitor = new Object();
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
executorService.submit(new Task(monitor));
}
executorService.shutdown();
}
}
class Task implements Runnable {
Object monitor;
public Task(Object monitor) {
this.monitor = monitor;
}
void syncMethod() {
synchronized (monitor) {
System.out.println("This is the sync method causing issues");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
syncMethod();
}
}https://stackoverflow.com/questions/49809666
复制相似问题