package net.ranides.assira.ee;

import net.ranides.assira.collection.maps.CacheMap;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Singleton;
import javax.ejb.Startup;

/**
 * Singleton which starts automatically as deamon thread and cleans CacheMap in the background.
 * Cleaning cache in the background is a bit better than cleaning just at the moment when user reads from cache.
 */
@Singleton
@Startup
public class CacheMapCleaner {

    private Thread thread;

    /**
     * Starts deamon thread. Called automatically by Java EE container at application startup.
     */
    @PostConstruct
    public void init() {
        thread = new Thread(() -> CacheMap.cleanup(true), "assira.ee cache cleanup");
        thread.setDaemon(true);
        thread.start();
    }

    /**
     * Stops deamon thread. Called automatically by Java EE container at application shutdown.
     */
    @PreDestroy
    public void destroy() {
        thread.interrupt();
    }

}
