Class NamedThreadFactory

java.lang.Object
com.clumd.projects.java_common_utils.base_enhancements.NamedThreadFactory
All Implemented Interfaces:
ThreadFactory

public class NamedThreadFactory extends Object implements ThreadFactory
This is used in order to re-name the pool and workers who are spawned into it.
  • Constructor Details

    • NamedThreadFactory

      public NamedThreadFactory(String poolName)
      Used to give the pool a name so that log messages can be more contextual. Though the Pool name is customisable, thread names in this pool will be called "handler"s.
      Parameters:
      poolName - What to name the pool.
    • NamedThreadFactory

      public NamedThreadFactory(String poolName, String prefix)
      Used to give the pool a name so that log messages make more sense - using a prefix for further context.
      Parameters:
      poolName - What to name the pool.
      prefix - An additional prefix onto the thread to be used for further context clarification.
  • Method Details

    • create

      public static Thread create(@NonNull @NonNull String newThreadName, @NonNull @NonNull Runnable runnable)
      A static version of newThread(String, Runnable), to save creating a new instance if you only want one custom named thread.
      Parameters:
      newThreadName - The name the associated thread should be given.
      runnable - The actual work to carry out under the given name.
      Returns:
      A new named thread ready to be executed.
    • overrideNextThreadName

      public void overrideNextThreadName(@NonNull @NonNull String withName)
      Used to tell this factory that the next thread should ignore the standard naming convention and just call it whatever this method is passed. This should be a single-shot method, which will revert back to the naming pattern after the next thread has been created with this as its name.
      Parameters:
      withName - The name the next thread should use.
    • newThread

      public Thread newThread(@NonNull @NonNull Runnable runnable)
      Specified by:
      newThread in interface ThreadFactory
    • newThread

      public Thread newThread(@NonNull @NonNull String newThreadName, @NonNull @NonNull Runnable runnable)
      This is a convenience method to create a new thread from a lambda, with a given name, using a single method - rather than having to explicitly call the override and clear next thread name methods.
      Parameters:
      newThreadName - The name the associated thread should be given.
      runnable - The actual work to carry out under the given name.
      Returns:
      A new named thread ready to be executed.
    • clearOverriddenName

      public void clearOverriddenName()
      Used in the event that you want to cancel a thread name overriding.