Flexible injector inside the thread
I have doubts about using Guice. I have a class that I call Main
, which is a constructor injected with Guice, and a method that every time it is called creates a stream object o of the class AppThread
. AppThread
is a private class inside Main
. The problem is, inside the thread execution, I want to create a class object ClassX
. This object is a constructor introduced using Guice. I don't know what is the best form for inserting objects ClassX
. My first solution is to inject Injector
inside Main
, and inside the stream use an injector to inject class objects ClassX
.
Is there a cleaner approach for injecting dependencies within a thread?
thank
Instead of having your own subclass Thread
(which is still not recommended), you should write your "stream code" as a regular object that implements Runnable
. Your class Main
should inject this class (or you can actually inject Provider<MyRunnable>
if you need to instantiate an unknown number of them). Then your class Main
can build new Thread(myRunnable)
and everything should fit well.
public class MyMainClass {
@Inject
MyMainClass(Provider<MyRunnable> runnableProvider) { ... }
public void spawnThread() {
new Thread(runnableProvider.get()).start();
}
}
public class MyRunnable implements Runnable {
@Inject
MyRunnable(ClassX myX) { ... }
public void run() {
... do work ...
}
}
source to share