Reputation: 1537
I am a bit confused about how to solve the following problem:
I have a big (java se) application, which is based on the producer-consumer model and works mostly multithreaded. E.g. 10 threads are fetching messages, 40 threads are consuming messages. Now i have objects, which need to be shared in all threads, like a ThreadPoolExecutor. Pseudo Code:
ExecutorService execService =
new ThreadPoolExecutor(10, 10, 1, TimeUnit.SECONDS, some_queue);
execService.submit(new Consumer(sharedEntityManagerFactory)
These consumer threads submit every fetched message to another ThreadPoolExecutor, which has threads to process this message.
Now my question is, how to i effectively share objects across all threads (for example an EntityManagerFactoryObject (which is supposed to be a singleton i think) for DataAccessObjects) ? That's only an example it could also be a simple list, or a more complex POJO.
Would a possible(/good) solution be to do this in with dependency injection (JavaSE)? As far as i know it would be a greate solution, but the objects are only created once, and the threads only hold the reference, not a truly new object.
Upvotes: 3
Views: 1080
Reputation: 30733
The details vary, based on the dependency injection library you plan to use. But most/all of them supply the possibility of specifying that an injected object is singleton, that is: the library will only create it once, and the same instance will be injected too all the clients.
Upvotes: 2