samedi 30 avril 2016

java concurrency - singleton design with a monitor thread

I have a singleton class thus

public final class HandlerCache {
    //the cache maintains a handler per thread 
    private final Map<Thread, Handler> cache = new ConcurrentHashMap<>();

    private final Thread monitor;

    private static final HandlerCache INSTANCE = new HandlerCache();

    private HandlerCache() {
        monitor = new Thread() {
        //periodically monitor cache and close handlers when a thread has died
        }
        monitor.start()
    }

    public static HandlerCache getInstance() {
        return INSTANCE;
    }

    public Handler getHandler() throws Exception {
        final Thread thread = Thread.currentThread();
        Handler handler = cache.get(thread);

        if (!(handler == null))
            return handler;

        handler = HandlerFactory.get(getHandlerFromName(thread.getName()));
        cache.put(thread, handler);
        return handler;
    }

}

I am leaking the singleton instance to the monitor thread before the constructor is finished, what is the better way ?

Will making cache volatile will fix the issue ?

Aucun commentaire:

Enregistrer un commentaire