Multithreading issue with executeService for Dependency Injection inside Runnable class

Hi…
I want to use executeService in a bean for multi threading…

        ExportHelper exportHelper = new ExportHelper();
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        executorService.execute(exportHelper);
        executorService.shutdown();

The Self managed ExportHelper Class implements Runnable, in which we are injecting the bean inside the ExportHelper class specified below.

public class ExportHelper implements Runnable {

    @Autowired
    private NewBean newBean;
    private static final Logger log = LoggerFactory.getLogger(ExportHelper.class);

    @Override
    public void run() {
       String name = newBean.getName();
       log.info(name);
    }
}

@Component
public class NewBean {
    public String getName() {
        return "Hello World!";
    }
}

I am unable to use the newBean service inside the ExportHelper class and getting the below error,

Exception in thread “pool-3-thread-1” java.lang.NullPointerException
at com.company.multithread.core.ExportHelper.run(ExportHelper.java:16)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)

Note: I presume it is because of improper dependency injection (invalid SecurityContext) inside the ExportHelper class, So, plz help how to execute multithreading on Runnable class with dependency injection.

Thanks.

Dependency injection with @Autowired works only in beans (classes annotated with @Component, etc.), that’s why you get NPE.

Why wouldn’t make the ExportHelper a bean?

@Component
public class ExportHelper implements Runnable {
// ...

Of course then you should also inject it or get through ApplicationContext instead of using new.
If it needs some state which is not thread-safe, make it a prototype:

@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ExportHelper implements Runnable {
// ...

and get via ApplicationContext:

ExportHelper exportHelper = applicationContext.getBean(ExportHelper.class);
//...
1 Like

Hi @krivopustov ,
Applicated your solution… Thanks…