Similaire à Background Thread for a Tomcat servlet app mais je suis à la recherche d'une solution spécifique Java EE 7.Comment exécuter/gérer le thread d'arrière-plan du conteneur dans Java EE 7+?
0
A
Répondre
1
C'est ce que je suis finalement arrivé avec pour wildfly 11 (Java EE 7) sans utiliser les modifications de configuration/ajouts à beans.xml/web.xml:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.enterprise.concurrent.ManagedThreadFactory;
@Startup
@Singleton
public class IndexingTask implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(IndexingTask.class);
private Thread taskThread = null;
private final CountDownLatch shutdownLatch = new CountDownLatch(1);
@Resource
private ManagedThreadFactory threadFactory;
@PostConstruct
public void postConstruct() {
taskThread = threadFactory.newThread(this);
taskThread.start();
}
@PreDestroy
public void preDestroy(){
shutdownLatch.countDown();
try {
taskThread.join();
} catch (InterruptedException ex) {
LOG.warn("interrupted while waiting for " + taskThread + " to shut down", ex);
}
}
@Override
public void run() {
LOG.info("started");
try {
while (!shutdownLatch.await(100, TimeUnit.MILLISECONDS)) {
}
} catch (InterruptedException ex) {
LOG.warn("", ex);
}
LOG.info("stopped");
}
}
https://gruust.stream/2017/10/15/how-to-run-manage-a-container-background-thread-in-java-ee-7-
Voir aussi Java EE 7 containers: initialize bean at startup without adding it to beans.xml?