All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gateway.connector.utils.ThreadNameFactory Maven / Gradle / Ivy

package com.gateway.connector.utils;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ThreadNameFactory implements ThreadFactory{
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(0);
    private final String namePrefix;
    private final boolean daemon;
	protected final Logger logger = LoggerFactory.getLogger(getClass());
    public ThreadNameFactory(String namePreFix)
    {
       this(namePreFix, false);
    }

    public ThreadNameFactory(String namePreFix, boolean daemon)
    {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread()
                .getThreadGroup();
        this.namePrefix = namePreFix + "-thread-";
        this.daemon = daemon;
    }

    @Override
    public Thread newThread(Runnable r)
    {
        Thread t = new Thread(group, r, namePrefix
                + threadNumber.getAndIncrement(), 0);
        t.setUncaughtExceptionHandler(new ExceptionHandler());
        if(daemon) {
           t.setDaemon(daemon);
        }else{
            if (t.isDaemon()) {
                t.setDaemon(false);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
        }
        return t;
    }

    public String getNamePrefix() {
        return namePrefix;
    }
    public class ExceptionHandler implements UncaughtExceptionHandler {
		public void uncaughtException(Thread t, Throwable e) {
			logger.error("An exception has been captured\n");
			logger.error("Thread: {}\n", t.getName());
			logger.error("Exception: {}: {}\n", e.getClass().getSimpleName(), e.getMessage());
			logger.error("Stack Trace: {}\n", e);
			logger.error("Thread status: {}\n", t.getState());
		}
	}
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy