在我的Web应用程序中,我有一个后台服务.此服务使用包含Engine类的Generator类和配置为使用多个线程并接受GeneratorTasks的ExecutorService.
@Component
public class Generator {
@Autowired
private Engine heavyEngine;
private ExecutorService exec = Executors.newFixedThreadPool(3);
//I actually pass the singleton instance Generator class into the task.
public void submitTask(TaskModel model, TaskCallback callback) {
this.exec.submit(new GeneratorTask(model, this, callback));
}
}
@Component
public class Engine {
public Engine() {
//time-consuming initialization code here
}
}
public class GeneratorTask implements Callable {
public GeneratorTask(TaskModel m, Generator g, ReceiptCallback c) {
this.m = m;
this.generator = g;
this.c = c;
}
public String call() throws Exception {
//This actually calls the Engine class of the generator.
//Maybe I should have passed the Engine itself?
this.generator.runEngine(c);
}
}
Engine类需要很长时间才能初始化,所以理想情况下我希望每个线程只初始化一次.我不能只使它成为单例实例,因为实例不能跨多个线程共享(它依赖于顺序处理).在处理任务完成后,重用实例是完全可以的.
我正在考虑将私有Engine HeavyEngine变量作为ThreadLocal变量.但是,我也是Spring的新手,所以我想知道是否有其他方法可以使用Spring注释注入ThreadLocal变量.我已经看过确定bean的范围,但是我不确定如何根据我的设计去做.
任何关于如何改进我的设计的指导将不胜感激.