Singleton注释 - 在post-destroy之前创建的新单例调用

时间:2015-09-29 08:27:37

标签: java java-ee jax-rs glassfish-4

我使用单身人士来使用JODConverter。问题是,当收到新请求时,会创建一个新的单例,而旧的单例被销毁,但顺序不匹配:在@PostContruct之前调用新单例的@PreDestroy方法旧方法。

这会导致失败,因为服务器已在JodConverter运行。

以下是代码:

@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
@Startup
@Singleton
public class FileConverter {

    private static final String PROPERTIES_FILE = "path/conf.properties";
    private static final String OO_HOME_KEY = "viewers.ooHome";
    private static final String OO_PORT_KEY = "viewers.ooPort";
    private static final Logger LOGGER = Logger.getLogger(FileConverter.class.getName());

    private OfficeManager officeManager;

    @PostConstruct
    private void init() {
        InputStream inputStream = null;
        try {
            Properties properties = new Properties();
            inputStream = FileConverter.class.getResourceAsStream(PROPERTIES_FILE);
            properties.load(inputStream);
            String ooHome = properties.getProperty(OO_HOME_KEY);
            int ooPort = Integer.parseInt(properties.getProperty(OO_PORT_KEY));
            officeManager = new DefaultOfficeManagerConfiguration()
                    .setOfficeHome(new File(ooHome))
                    .setPortNumber(ooPort)
                    .buildOfficeManager();
            officeManager.start();
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
            throw new RuntimeException(e);
        } finally {
            try{
                if(inputStream!=null){
                    inputStream.close();
                }
            }catch (IOException e){
                LOGGER.log(Level.FINEST, null, e);
            }
        }
    }

    @PreDestroy
    private void close(){
        officeManager.stop();
    }

编辑:

我已经从javax.ejb.Singleton更改为javax.inject.Singleton并自行管理并发。非常感谢@peeskillet

0 个答案:

没有答案