user1151835
user1151835

Reputation:

Guice injector inside a thread

I have a doubt using Guice. I have a class that I call Main that is constructor injected using Guice and a method that every time that is called creates an o thread object of class AppThread. AppThread is a private class inside Main. The problem is that inside the execution of the thread I want to create an object of class ClassX. This object is constructor injected using Guice. I don't know what's the best form to inject the objects of ClassX. My first solution is inject the Injector inside Main and inside the thread use the injector to inject the objects of class ClassX.

Does exists a cleaner approach to inject the dependences inside the thread?

Thanks

Upvotes: 3

Views: 3821

Answers (1)

Steven Schlansker
Steven Schlansker

Reputation: 38536

Instead of having your own subclass of Thread (which is discouraged anyway) you should write your "thread code" as a regular object that implements Runnable. Your Main class should inject this class (or you can actually inject a Provider<MyRunnable> if you need to instantiate an unknown number of them). Then your Main class can create a new Thread(myRunnable) and it should all fit together nicely.

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 ...
    }
}

Upvotes: 5

Related Questions