In my web application, I have a background service. This service uses the Generator class, which contains the Engine and ExecutorService classes, configured to use multiple threads and accept GeneratorTasks.
@Component public class Generator { @Autowired private Engine heavyEngine; private ExecutorService exec = Executors.newFixedThreadPool(3);
The Engine class takes a long time to initialize, so I ideally want to initialize it only once per thread. I can't just make it an instance of singleton, because the instance cannot be used for multiple threads (it relies on sequential processing). It is great to reuse an instance, although after completing the processing task.
I was thinking of making the private Engine heavyEngine variable a ThreadLocal variable. However, I'm also new to Spring, so I was wondering if there could be another way to insert ThreadLocal variables using Spring annotations. I reviewed the scope of the bean before request , but I'm not sure how I can do this based on my design.
Any recommendations for improving my design would be appreciated.
java spring multithreading
Jensen ching
source share