Say I have a class:
public class MyTask implements Runnable { @Inject private Fizz fizz;
And I have another class:
public class MyTaskDispatcher { @Inject private ThreadFactory threadFactory; private Executor executor;
So Guice injects MyTask using Fizz , and also introduces MyTaskDispatcher with ThreadFactory , which is then used to create and execute the MyTask instances that it passed. And, since it is a cached pool, it only creates a new thread when it is needed but not available.
I wonder how Guice behaves in a multi-threaded environment when we insert Fizz as single or non-single.
Let's start with the non-Singleton for-instance:
public class MyAppModule extends AbstractModule { @Override public void configure() { bind(Fizz.class).to(FizzImpl.class);
Now let's say that the application has been running for some time, and 3 separate MyTask have been sent, and thus there are 3 running threads. Since we did not ask Guice to introduce Fizz es as a singleton, I assume that each thread has its own copy of the input of FizzImpl , and we do not need to add any synchronize type code to prevent 3 FizzImpl from colliding and causing problems with the stream.
But what happens when we make a FizzImpl Guice injection as a single ???? Now, in MyAppModule :
@Provides @Singleton FizzImpl providesFizz() { return new FizzImpl(true, Buzz.ALWAYS, 35); }
If Guice provides only one global singleton instance from FizzImpl , what are the subsequent branches of this FizzImpl โcopyโ (if that's the right word for it) inside each of the 3 generated threads? What are the pitfalls to watch out for? What are the ways to deal with these pitfalls? Thanks in advance.