Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


1 Answers

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 ...
    }
}
like image 85
Steven Schlansker Avatar answered Jan 26 '26 05:01

Steven Schlansker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!