如何运行/ Java EE中7+管理容器后台线程?

问题描述 投票:0回答:1

类似Background Thread for a Tomcat servlet app,但我正在寻找一个Java EE 7的具体解决方案。

javabeans java-ee-7
1个回答
1
投票

这是我终于想出了WildFly 11(的Java EE 7)不使用任何配置更改/补充的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://javagc.leponceau.org/2017/10/how-to-runmanage-container-background.html

参见Java EE 7 containers: initialize bean at startup without adding it to beans.xml?

© www.soinside.com 2019 - 2024. All rights reserved.