Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Bean running in its own thread

Within my web application, I am trying to create a directory polling bean using Java SDK7 WatchService. What I would like to achieve is to run this bean in its own thread so that it does not block the application. Something like:

  <bean id="directoryPoller" class="org...MyDirectoryPoller" scope="thread"/>
like image 211
Vojtěch Avatar asked Mar 03 '12 08:03

Vojtěch


2 Answers

I am afraid you will have to create this thread manually with Spring:

<bean id="pollThread" class="java.lang.Thread" init-method="start" destroy-method="interrupt">
    <constructor-arg ref="watchServiceRunnableWrapper"/>
</bean>

<bean id="watchServiceRunnableWrapper" class="WatchServiceRunnableWrapper">
    <constructor-arg ref="watchService"/>
</bean>

<bean id="WatchService" class="java.nio.file.WatchService" destroy-method="close"/>

The WatchServiceRunnableWrapper is simple:

public class WatchServiceRunnableWrapper implements Runnable {

    private WatchService WatchService;

    public WatchServiceRunnableWrapper(WatchService watchService) {
        this.watchService = watchService;
    }

    public void run() {
        watchService.poll();
        //
    }
}

I haven't tested it, but it more-or-less should work and shutdown gracefully.

like image 65
Tomasz Nurkiewicz Avatar answered Oct 14 '22 12:10

Tomasz Nurkiewicz


I'm not familiar with Java 7's WatchService, but you could use Springs' scheduling support for this. Here's yet another tutorial and googling for something like Spring Scheduled probably finds loads more.

like image 37
esaj Avatar answered Oct 14 '22 12:10

esaj