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

com.groupbyinc.common.util.DefaultThreadFactory Maven / Gradle / Ivy

The newest version!
package com.groupbyinc.common.util;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ThreadFactory that keeps the current thread's name to make logs easier to follow and grep
 */
public class DefaultThreadFactory implements ThreadFactory {

  private final AtomicInteger threadNumber = new AtomicInteger(0);
  private ThreadFactory defaultFactory = Executors.defaultThreadFactory();
  private String name;
  private boolean includeThreadNumber;
  private boolean includeParentThreadName;

  public DefaultThreadFactory(String name, boolean includeThreadNumber, boolean includeParentThreadName) {
    this.name = name;
    this.includeThreadNumber = includeThreadNumber;
    this.includeParentThreadName = includeParentThreadName;
  }

  @Override
  public Thread newThread(Runnable r) {
    Thread t = defaultFactory.newThread(r);
    StringBuilder overrideName = new StringBuilder();
    if (includeParentThreadName) {
      overrideName.append(Thread.currentThread().getName());
      overrideName.append(":");
    }
    overrideName.append(name);
    if (includeThreadNumber) {
      overrideName.append(":");
      overrideName.append(threadNumber.incrementAndGet());
    }
    t.setName(overrideName.toString());
    return t;
  }
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy