Class NotifyingThread

  • All Implemented Interfaces:
    java.lang.Runnable, java.lang.Thread.UncaughtExceptionHandler

    public class NotifyingThread
    extends java.lang.Thread
    implements java.lang.Thread.UncaughtExceptionHandler
    NotifyingThread provides an specialised class on threading that adds more options to the current available threading models:
    • Notifying: sometimes we want to get notified when a Thread completes its execution, but the most we can do is just wait until its completion for going to the next step in our execution. NotifyingThread provides a fast, powerful class for getting notified when threads we want finish, just by subscribing to the listener classes implementing the OnThreadCompletedListener interface.
    • Fast development: it is very common that we declare the following:
                   
                   // Class: ExampleClass
                   public void functionWithHeavyLoad(final ArrayList<Double> params) {
                       final Integer value = new Random().nextInt(1337);
                       new Thread(new Runnable() {
                            public void run() {
                                double veryBigValue = params.get(0);
                                ExampleClass.this.mField = ExampleClass.this.doVeryBigMathCalc(value,
                                veryBigValue);
                            }
                       }).start();
                   }
                   
       
      With NotifyingThread is as simple as declaring the method we are going to use, wrap params using ArgumentParser and returning the values if necessary. So, the latest code will just be:
                   
                   // Class: ExampleClass
                   public double doVeryBigMathCalc(ArgumentParser args) {
                       int firstValue = args.getInt("firstParam");
                       double secondValue = args.getDouble("secondParam");
                       // do calculations and store its result at: double result;
                       return result;
                   }
      
                   public void functionWithHeavyLoad(final ArrayList<Double> params) {
                        final Integer value = new Random().nextInt(1337);
                        // Declare NotifyingThread, ArgumentParser and AtomicReference
                        NotifyingThread thread = new NotifyingThread();
                        ArgumentParser parser = new ArgumentParser(2);
                        AtomicReference<Double> result = new AtomicReference<>();
                        // Set params
                        parser.putParam("firstParam", value);
                        parser.putParam("secondParam", params.get(0));
                        // Set the executable by using lambdas
                        thread.setExecutable(this::doVeryBigMathCalc, parser, result);
                        // Start the thread
                        thread.start();
                        // Wait for the thread completion - we can define a listener for getting
                        notified.
                        System.out.println(result.get());
                   }
                   
               
    • Adaptive: NotifyingThread provides adaptive methods for setting up the executables, so you can use Consumer, Function, Runnable and Supplier.
    By default, this class uses its own Thread.UncaughtExceptionHandler for notifying subscribed classes that the thread has finished with an exception. If you want to use yours, just setup the UncaughtExceptionHandler with Thread.setUncaughtExceptionHandler(UncaughtExceptionHandler).

    In addition, this class supports async calling for subscribed classes when the threads finishes. Refer to async execution docs for more information.

    • Nested Class Summary

      • Nested classes/interfaces inherited from class java.lang.Thread

        java.lang.Thread.State, java.lang.Thread.UncaughtExceptionHandler
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static int DEFAULT_CAPACITY
      Default capacity of subscribed classes - normally, we only want one class to get notified when a thread completes.
      private java.util.concurrent.atomic.AtomicBoolean mShouldCallSubscribedClassesAsynchronously
      Whether the calling of subscribed classes must be done asynchronously or not.
      private java.util.ArrayList<OnThreadCompletedListener> mSubscribedClasses
      List of subscribed classes.
      private java.lang.Runnable mTarget
      Target that will be executed when Thread.start() is called.
      private static java.util.concurrent.atomic.AtomicInteger mThreadNumber
      Thread count number.
      static java.lang.String THREAD_PREFIX
      Thread prefix used when invoking "toString".
      • Fields inherited from class java.lang.Thread

        MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY
    • Constructor Summary

      Constructors 
      Constructor Description
      NotifyingThread()
      Allocates a new Thread object.
      NotifyingThread​(OnThreadCompletedListener... listeners)
      Allocates a new Thread object.
      NotifyingThread​(java.lang.Runnable target)
      Allocates a new Thread object.
      NotifyingThread​(java.lang.Runnable target, OnThreadCompletedListener... listeners)
      Allocates a new Thread object.
      NotifyingThread​(java.lang.Runnable target, java.lang.String name)
      Allocates a new Thread object.
      NotifyingThread​(java.lang.Runnable target, java.lang.String name, OnThreadCompletedListener... listeners)
      Allocates a new Thread object.
      NotifyingThread​(java.lang.String name)
      Allocates a new Thread object.
      NotifyingThread​(java.lang.String name, OnThreadCompletedListener... listeners)
      Allocates a new Thread object.
      NotifyingThread​(java.lang.ThreadGroup group, java.lang.Runnable target)
      Allocates a new Thread object.
      NotifyingThread​(java.lang.ThreadGroup group, java.lang.Runnable target, OnThreadCompletedListener... listeners)
      Allocates a new Thread object.
      NotifyingThread​(java.lang.ThreadGroup group, java.lang.Runnable target, java.lang.String name)
      Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.
      NotifyingThread​(java.lang.ThreadGroup group, java.lang.Runnable target, java.lang.String name, long stackSize)
      Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.
      NotifyingThread​(java.lang.ThreadGroup group, java.lang.Runnable target, java.lang.String name, long stackSize, OnThreadCompletedListener... listeners)
      Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.
      NotifyingThread​(java.lang.ThreadGroup group, java.lang.Runnable target, java.lang.String name, OnThreadCompletedListener... listeners)
      Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.
      NotifyingThread​(java.lang.ThreadGroup group, java.lang.String name)
      Allocates a new Thread object.
      NotifyingThread​(java.lang.ThreadGroup group, java.lang.String name, OnThreadCompletedListener... listeners)
      Allocates a new Thread object.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void addOnThreadCompletedListener​(OnThreadCompletedListener listener)
      Adds a new listener to the list of subscribed classes.
      void addOnThreadCompleteListener​(OnThreadCompletedListener... listeners)
      Adds new listeners to the list of subscribed classes at once.
      private void callSubscribedClasses​(java.lang.Thread thread, java.lang.Throwable exception)
      When a thread finishes, or an exception is thrown, this method is called by run() or uncaughtException(Thread, Throwable), the first one to occur.
      protected java.lang.Object clone()
      Throws CloneNotSupportedException as a Thread can not be meaningfully cloned.
      boolean equals​(java.lang.Object obj)
      Indicates whether some other object is "equal to" this one.
      int hashCode()
      Returns a hash code value for the object.
      private static int nextThreadNumber()
      Returns the corresponding thread number for a newly created NotifyingThread.
      void removeAllListeners()
      Un-subscribes all classes listening to this thread completion.
      boolean removeOnThreadCompletedListener​(OnThreadCompletedListener listener)
      Tries to remove the given listener from the list of subscribed classes, if present.
      void run()
      If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
      void setExecutable​(java.lang.Runnable runnable)
      Once after the NotifyingThread is created, this method can be used for setting the Runnable that will be executed when Thread.start() is called.
      void setExecutable​(java.util.function.Consumer<ArgumentParser> consumer, ArgumentParser args)
      Once after the NotifyingThread is created, this method can be used for setting the Runnable that will be executed when Thread.start() is called.
      void setExecutable​(java.util.function.Function<ArgumentParser,​?> function, ArgumentParser args, java.util.concurrent.atomic.AtomicReference result)
      Once after the NotifyingThread is created, this method can be used for setting the Runnable that will be executed when Thread.start() is called.
      void setExecutable​(java.util.function.Supplier supplier, java.util.concurrent.atomic.AtomicReference result)
      Once after the NotifyingThread is created, this method can be used for setting the Runnable that will be executed when Thread.start() is called.
      void setShouldCallSubscribedClassesAsynchronously​(boolean shouldCallAsynchronously)
      When passing true to this method, when run() finishes and subscribed classes are called, that call will be done on a new asynchronous thread.
      java.lang.String toString()
      Returns a string representation of this thread, including the thread's name, priority, and thread group.
      void uncaughtException​(java.lang.Thread thread, java.lang.Throwable exception)
      Method invoked when the given thread terminates due to the given uncaught exception.
      • Methods inherited from class java.lang.Thread

        activeCount, checkAccess, countStackFrames, currentThread, dumpStack, enumerate, getAllStackTraces, getContextClassLoader, getDefaultUncaughtExceptionHandler, getId, getName, getPriority, getStackTrace, getState, getThreadGroup, getUncaughtExceptionHandler, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, onSpinWait, resume, setContextClassLoader, setDaemon, setDefaultUncaughtExceptionHandler, setName, setPriority, setUncaughtExceptionHandler, sleep, sleep, start, stop, suspend, yield
      • Methods inherited from class java.lang.Object

        finalize, getClass, notify, notifyAll, wait, wait, wait
    • Field Detail

      • DEFAULT_CAPACITY

        public static final int DEFAULT_CAPACITY
        Default capacity of subscribed classes - normally, we only want one class to get notified when a thread completes.
        See Also:
        Constant Field Values
      • THREAD_PREFIX

        public static final java.lang.String THREAD_PREFIX
        Thread prefix used when invoking "toString".
        See Also:
        Constant Field Values
      • mThreadNumber

        private static final java.util.concurrent.atomic.AtomicInteger mThreadNumber
        Thread count number.
      • mShouldCallSubscribedClassesAsynchronously

        private java.util.concurrent.atomic.AtomicBoolean mShouldCallSubscribedClassesAsynchronously
        Whether the calling of subscribed classes must be done asynchronously or not.
        See Also:
        callSubscribedClasses(Thread, Throwable)
      • mTarget

        private java.lang.Runnable mTarget
        Target that will be executed when Thread.start() is called.
    • Constructor Detail

      • NotifyingThread

        public NotifyingThread()
        Allocates a new Thread object. This constructor has the same effect as NotifyingThread (null, null, gname), where gname is a newly generated name. Automatically generated names are of the form "NotifyingThread-"+n, where n is an integer.
      • NotifyingThread

        public NotifyingThread​(java.lang.Runnable target)
        Allocates a new Thread object. This constructor has the same effect as NotifyingThread (null, target, gname), where gname is a newly generated name. Automatically generated names are of the form "NotifyingThread-"+n, where n is an integer.
        Parameters:
        target - the object whose run method is invoked when this thread is started. If null, this classes run method does nothing.
      • NotifyingThread

        public NotifyingThread​(java.lang.Runnable target,
                               @NotNull
                               OnThreadCompletedListener... listeners)
        Allocates a new Thread object. This constructor has the same effect as NotifyingThread (null, target, gname, listeners), where gname is a newly generated name. Automatically generated names are of the form "NotifyingThread-"+n, where n is an integer.
        Parameters:
        target - the object whose run method is invoked when this thread is started. If null, this classes run method does nothing.
        listeners - an array of listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at the OnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable) method, giving both Runnable of the just finished thread and Throwable with any exception that occurred during execution.
      • NotifyingThread

        public NotifyingThread​(@Nullable
                               java.lang.ThreadGroup group,
                               java.lang.Runnable target)
        Allocates a new Thread object. This constructor has the same effect as NotifyingThread (group, target, gname), where gname is a newly generated name. Automatically generated names are of the form "NotifyingThread-"+n, where n is an integer.
        Parameters:
        group - the thread group. If null and there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager or SecurityManager.getThreadGroup() returns null, the group is set to the current thread's thread group.
        target - the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
        Throws:
        java.lang.SecurityException - if the current thread cannot create a thread in the specified thread group
      • NotifyingThread

        public NotifyingThread​(@Nullable
                               java.lang.ThreadGroup group,
                               java.lang.Runnable target,
                               @NotNull
                               OnThreadCompletedListener... listeners)
        Allocates a new Thread object. This constructor has the same effect as NotifyingThread (group, target, gname, listeners) , where gname is a newly generated name. Automatically generated names are of the form "NotifyingThread-"+n, where n is an integer.
        Parameters:
        group - the thread group. If null and there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager or SecurityManager.getThreadGroup() returns null, the group is set to the current thread's thread group.
        target - the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
        listeners - an array of listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at the OnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable) method, giving both Runnable of the just finished thread and Throwable with any exception that occurred during execution.
        Throws:
        java.lang.SecurityException - if the current thread cannot create a thread in the specified thread group
      • NotifyingThread

        public NotifyingThread​(@Nullable
                               java.lang.ThreadGroup group,
                               @NotNull
                               java.lang.String name,
                               @NotNull
                               OnThreadCompletedListener... listeners)
        Allocates a new Thread object. This constructor has the same effect as NotifyingThread (group, null, name, listeners).
        Parameters:
        group - the thread group. If null and there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager or SecurityManager.getThreadGroup() returns null, the group is set to the current thread's thread group.
        name - the name of the new thread.
        listeners - an array of listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at the OnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable) method, giving both Runnable of the just finished thread and Throwable with any exception that occurred during execution.
        Throws:
        java.lang.SecurityException - if the current thread cannot create a thread in the specified thread group
      • NotifyingThread

        public NotifyingThread​(@NotNull
                               java.lang.String name)
        Allocates a new Thread object. This constructor has the same effect as NotifyingThread (null, null, name).
        Parameters:
        name - the name of the new thread
      • NotifyingThread

        public NotifyingThread​(java.lang.Runnable target,
                               java.lang.String name,
                               @NotNull
                               OnThreadCompletedListener... listeners)
        Allocates a new Thread object. This constructor has the same effect as NotifyingThread (null, target, name, listeners).
        Parameters:
        target - the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
        name - the name of the new thread.
        listeners - an array of listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at the OnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable) method, giving both Runnable of the just finished thread and Throwable with any exception that occurred during execution.
      • NotifyingThread

        public NotifyingThread​(@Nullable
                               java.lang.ThreadGroup group,
                               @NotNull
                               java.lang.String name)
        Allocates a new Thread object. This constructor has the same effect as NotifyingThread (group, null, name).
        Parameters:
        group - the thread group. If null and there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager or SecurityManager.getThreadGroup() returns null, the group is set to the current thread's thread group.
        name - the name of the new thread.
        Throws:
        java.lang.SecurityException - if the current thread cannot create a thread in the specified thread group
      • NotifyingThread

        public NotifyingThread​(@Nullable
                               java.lang.ThreadGroup group,
                               java.lang.Runnable target,
                               @NotNull
                               java.lang.String name,
                               @NotNull
                               OnThreadCompletedListener... listeners)
        Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.

        If there is a security manager, its checkAccess method is invoked with the ThreadGroup as its argument.

        In addition, its checkPermission method is invoked with the RuntimePermission("enableContextClassLoaderOverride") permission when invoked directly or indirectly by the constructor of a subclass which overrides the getContextClassLoader or setContextClassLoader methods.

        The priority of the newly created thread is set equal to the priority of the thread creating it, that is, the currently running thread. The method setPriority may be used to change the priority to a new value.

        The newly created thread is initially marked as being a daemon thread if and only if the thread creating it is currently marked as a daemon thread. The method setDaemon may be used to change whether or not a thread is a daemon.

        Parameters:
        group - the thread group. If null and there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager or SecurityManager.getThreadGroup() returns null, the group is set to the current thread's thread group.
        target - the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
        name - the name of the new thread.
        listeners - an array of listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at the OnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable) method, giving both Runnable of the just finished thread and Throwable with any exception that occurred during execution.
        Throws:
        java.lang.SecurityException - if the current thread cannot create a thread in the specified thread group or cannot override the context class loader methods.
      • NotifyingThread

        public NotifyingThread​(java.lang.Runnable target,
                               java.lang.String name)
        Allocates a new Thread object. This constructor has the same effect as NotifyingThread (null, target, name).
        Parameters:
        target - the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
        name - the name of the new thread.
      • NotifyingThread

        public NotifyingThread​(@Nullable
                               java.lang.ThreadGroup group,
                               java.lang.Runnable target,
                               @NotNull
                               java.lang.String name)
        Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.

        If there is a security manager, its checkAccess method is invoked with the ThreadGroup as its argument.

        In addition, its checkPermission method is invoked with the RuntimePermission("enableContextClassLoaderOverride") permission when invoked directly or indirectly by the constructor of a subclass which overrides the getContextClassLoader or setContextClassLoader methods.

        The priority of the newly created thread is set equal to the priority of the thread creating it, that is, the currently running thread. The method setPriority may be used to change the priority to a new value.

        The newly created thread is initially marked as being a daemon thread if and only if the thread creating it is currently marked as a daemon thread. The method setDaemon may be used to change whether or not a thread is a daemon.

        Parameters:
        group - the thread group. If null and there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager or SecurityManager.getThreadGroup() returns null, the group is set to the current thread's thread group.
        target - the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
        name - the name of the new thread.
        Throws:
        java.lang.SecurityException - if the current thread cannot create a thread in the specified thread group or cannot override the context class loader methods.
      • NotifyingThread

        public NotifyingThread​(@Nullable
                               java.lang.ThreadGroup group,
                               java.lang.Runnable target,
                               @NotNull
                               java.lang.String name,
                               long stackSize)
        Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.

        This constructor is identical to NotifyingThread(ThreadGroup, Runnable, String) with the exception of the fact that it allows the thread stack size to be specified. The stack size is the approximate number of bytes of address space that the virtual machine is to allocate for this thread's stack. The effect of the stackSize parameter, if any, is highly platform dependent.

        On some platforms, specifying a higher value for the stackSize parameter may allow a thread to achieve greater recursion depth before throwing a StackOverflowError. Similarly, specifying a lower value may allow a greater number of threads to exist concurrently without throwing an OutOfMemoryError (or other internal error). The details of the relationship between the value of the stackSize parameter and the maximum recursion depth and concurrency level are platform-dependent. On some platforms, the value of the stackSize parameter may have no effect whatsoever.

        The virtual machine is free to treat the stackSize parameter as a suggestion. If the specified value is unreasonably low for the platform, the virtual machine may instead use some platform-specific minimum value; if the specified value is unreasonably high, the virtual machine may instead use some platform-specific maximum. Likewise, the virtual machine is free to round the specified value up or down as it sees fit (or to ignore it completely).

        Specifying a value of zero for the stackSize parameter will cause this constructor to behave exactly like the Thread(ThreadGroup, Runnable, String) constructor.

        Due to the platform-dependent nature of the behavior of this constructor, extreme care should be exercised in its use. The thread stack size necessary to perform a given computation will likely vary from one JRE implementation to another. In light of this variation, careful tuning of the stack size parameter may be required, and the tuning may need to be repeated for each JRE implementation on which an application is to run.

        Implementation note: Java platform implementers are encouraged to document their implementation's behavior with respect to the stackSize parameter.

        Parameters:
        group - the thread group. If null and there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager or SecurityManager.getThreadGroup() returns null, the group is set to the current thread's thread group.
        target - the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
        name - the name of the new thread.
        stackSize - the desired stack size for the new thread, or zero to indicate that this parameter is to be ignored.
        Throws:
        java.lang.SecurityException - if the current thread cannot create a thread in the specified thread group
        Since:
        1.4
      • NotifyingThread

        public NotifyingThread​(@Nullable
                               java.lang.ThreadGroup group,
                               java.lang.Runnable target,
                               @NotNull
                               java.lang.String name,
                               long stackSize,
                               @NotNull
                               OnThreadCompletedListener... listeners)
        Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.

        This constructor is identical to NotifyingThread(ThreadGroup, Runnable, String) with the exception of the fact that it allows the thread stack size to be specified. The stack size is the approximate number of bytes of address space that the virtual machine is to allocate for this thread's stack. The effect of the stackSize parameter, if any, is highly platform dependent.

        On some platforms, specifying a higher value for the stackSize parameter may allow a thread to achieve greater recursion depth before throwing a StackOverflowError. Similarly, specifying a lower value may allow a greater number of threads to exist concurrently without throwing an OutOfMemoryError (or other internal error). The details of the relationship between the value of the stackSize parameter and the maximum recursion depth and concurrency level are platform-dependent. On some platforms, the value of the stackSize parameter may have no effect whatsoever.

        The virtual machine is free to treat the stackSize parameter as a suggestion. If the specified value is unreasonably low for the platform, the virtual machine may instead use some platform-specific minimum value; if the specified value is unreasonably high, the virtual machine may instead use some platform-specific maximum. Likewise, the virtual machine is free to round the specified value up or down as it sees fit (or to ignore it completely).

        Specifying a value of zero for the stackSize parameter will cause this constructor to behave exactly like the Thread(ThreadGroup, Runnable, String) constructor.

        Due to the platform-dependent nature of the behavior of this constructor, extreme care should be exercised in its use. The thread stack size necessary to perform a given computation will likely vary from one JRE implementation to another. In light of this variation, careful tuning of the stack size parameter may be required, and the tuning may need to be repeated for each JRE implementation on which an application is to run.

        Implementation note: Java platform implementers are encouraged to document their implementation's behavior with respect to the stackSize parameter.

        Parameters:
        group - the thread group. If null and there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager or SecurityManager.getThreadGroup() returns null, the group is set to the current thread's thread group.
        target - the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.
        name - the name of the new thread.
        stackSize - the desired stack size for the new thread, or zero to indicate that this parameter is to be ignored.
        listeners - an array of listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at the OnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable) method, giving both Runnable of the just finished thread and Throwable with any exception that occurred during execution.
        Throws:
        java.lang.SecurityException - if the current thread cannot create a thread in the specified thread group
        Since:
        1.4
    • Method Detail

      • nextThreadNumber

        private static int nextThreadNumber()
        Returns the corresponding thread number for a newly created NotifyingThread.
        Returns:
        int with the thread number.
      • setShouldCallSubscribedClassesAsynchronously

        public void setShouldCallSubscribedClassesAsynchronously​(boolean shouldCallAsynchronously)
        When passing true to this method, when run() finishes and subscribed classes are called, that call will be done on a new asynchronous thread.

        That has some advantages:

        • There is no blocking during execution.
        • Because of what explained above, all subscribed classes are called, even if there is any error and/or exception.
        • Thread is not blocked, so it can resume any execution or get immediately idle in a ThreadPoolExecutor.
        Also, it has some disadvantages:
        • Both starvation and race conditions may occur during the subscribed classes calling.
        • The exceptions occurred during the new thread generation are not handled.

        By default, that field is set to false, which is the normal execution of that type of listeners.

        Parameters:
        shouldCallAsynchronously - whether the calling to subscribed classes must be async or not.
      • removeOnThreadCompletedListener

        public boolean removeOnThreadCompletedListener​(@NotNull
                                                       OnThreadCompletedListener listener)
        Tries to remove the given listener from the list of subscribed classes, if present.
        Parameters:
        listener - class to remove.
        Returns:
        true when the item was present, false if there was no listener matching the one to delete.
      • removeAllListeners

        public void removeAllListeners()
        Un-subscribes all classes listening to this thread completion.
      • setExecutable

        public void setExecutable​(@NotNull
                                  java.util.function.Consumer<ArgumentParser> consumer,
                                  @NotNull
                                  ArgumentParser args)
        Once after the NotifyingThread is created, this method can be used for setting the Runnable that will be executed when Thread.start() is called.

        This class uses a Consumer, which is a type of Function which accepts one parameter and produces no output. They are void functions.

        The function that will be inside this declaration must follow the following syntax:

        
                 // Class name: ConsumerFunction
                 public void functionName(ArgumentParser arguments) {
                     // Obtain arguments here
                     int firstArgument = arguments.getInt("firstArgumentName");
                     // ...
                     String nArgument = arguments.getString("nArgumentName");
                     // Produce some result/attribute with the given params
                     this.fieldToModify = nArgument + String.valueOf(firstArgument);
                 }
                 
        That function will apply a Consumer function, which can be used as follows:
                     
                     public static void main(String[] args) {
                         ConsumerFunction consumer = new ConsumerFunction(); // Here goes your class
                         which contains the consumer function.
                         // Declare both NotifyingThread and ArgumentParser
                         NotifyingThread thread = new NotifyingThread();
                         ArgumentParser parser = new ArgumentParser(2); // can be as much params as
                         you need.
                         // Set values contained at ArgumentParser
                         parser.putParam("firstArgumentName", 9889);
                         parser.putParam("nArgumentName", "Javinator");
                         // Add the new executable to the NotifyingThread
                         thread.setExecutable(consumer::functionName, parser);
                         // DO NOT FORGET TO EXECUTE THE THREAD
                         thread.start();
                         // -----------------------------------
                         // "fieldToModify" IN "ConsumerFunction" WILL BE:
                         // Javinator9889
                     }
                     
                 
        Parameters:
        consumer - function that follows the implementation described at the full documentation.
        args - arguments that receive that function.
        See Also:
        ArgumentParser
      • setExecutable

        public void setExecutable​(@NotNull
                                  java.lang.Runnable runnable)
        Once after the NotifyingThread is created, this method can be used for setting the Runnable that will be executed when Thread.start() is called.

        This class uses a Runnable, which is a type of Function which accepts no parameters and produces no output. They are void functions.

        The function that will be inside this declaration must follow the following syntax:

        
                 // Class name: RunnableFunction
                 public void functionName() {
                     // Useful for working with class fields once an operation is completed.
                     this.fieldToModify = "Javinator9889";
                 }
                 
        That function will apply a Runnable function, which can be used as follows:
                     
                     public static void main(String[] args) {
                         RunnableFunction runnable = new RunnableFunction(); // Here goes your class
                         which contains the runnable function.
                         // Declare a NotifyingThread
                         NotifyingThread thread = new NotifyingThread();
                         // Add the new executable to the NotifyingThread
                         thread.setExecutable(runnable::functionName);
                         // DO NOT FORGET TO EXECUTE THE THREAD
                         thread.start();
                         // -----------------------------------
                         // "fieldToModify" IN "RunnableFunction" WILL BE:
                         // Javinator9889
                     }
                     
                 
        Parameters:
        runnable - function that follows the implementation described at the full documentation.
      • setExecutable

        public void setExecutable​(@NotNull
                                  java.util.function.Supplier supplier,
                                  @NotNull
                                  java.util.concurrent.atomic.AtomicReference result)
        Once after the NotifyingThread is created, this method can be used for setting the Runnable that will be executed when Thread.start() is called.

        This class uses a Supplier, which is a type of Function which accepts no parameters and produces an output. Also, this type of functions are very similar to Future.

        The function that will be inside this declaration must follow the following syntax:

        
                 // Class name: SupplierFunction
                 public int functionName() {
                     // Produce some result/attribute with the class fields'
                     return this.fieldToProduce;
                 }
                 
        That function will apply a Supplier function, which can be used as follows:
                     
                     public static void main(String[] args) {
                         SupplierFunction supplier = new SupplierFunction(); // Here goes your class
                         which contains the supplier function.
                         // Declare both NotifyingThread and AtomicReference, which will contain
                         the result.
                         NotifyingThread thread = new NotifyingThread();
                         AtomicReference<Integer> result = new AtomicReference<>();
                         // Add the new executable to the NotifyingThread
                         thread.setExecutable(supplier::functionName, result);
                         // DO NOT FORGET TO EXECUTE THE THREAD
                         thread.start();
                         // ... wait until termination
                         System.out.println(result.get()); // The obtained result.
                         // -----------------------------------
                     }
                     
                 
        Parameters:
        supplier - function that follows the implementation described at the full documentation.
        result - AtomicReference that will contain the supplier result.
        See Also:
        AtomicReference
      • setExecutable

        public void setExecutable​(@NotNull
                                  java.util.function.Function<ArgumentParser,​?> function,
                                  @NotNull
                                  ArgumentParser args,
                                  @NotNull
                                  java.util.concurrent.atomic.AtomicReference result)
        Once after the NotifyingThread is created, this method can be used for setting the Runnable that will be executed when Thread.start() is called.

        This class uses a Function, which is a type of Function which accepts one parameter and produces one output. They are very similar to Future, as those functions receive zero or more args and produce a result.

        The function that will be inside this declaration must follow the following syntax:

        
                 // Class name: FunctionFunction
                 public String functionName(ArgumentParser arguments) {
                     // Obtain arguments here
                     int firstArgument = arguments.getInt("firstArgumentName");
                     // ...
                     String nArgument = arguments.getString("nArgumentName");
                     // Produce some result/attribute with the given params
                     this.fieldToModify = nArgument + String.valueOf(firstArgument);
                     return this.fieldToModify;
                 }
                 
        That function will apply a Function function, which can be used as follows:
                     
                     public static void main(String[] args) {
                         FunctionFunction function = new FunctionFunction(); // Here goes your class
                         which contains the function function.
                         // Declare NotifyingThread, ArgumentParser and AtomicReference
                         NotifyingThread thread = new NotifyingThread();
                         ArgumentParser parser = new ArgumentParser(2); // can be as much params as
                         you need.
                         AtomicReference<String> result = new AtomicReference<>();
                         // Set values contained at ArgumentParser
                         parser.putParam("firstArgumentName", 9889);
                         parser.putParam("nArgumentName", "Javinator");
                         // Add the new executable to the NotifyingThread
                         thread.setExecutable(function::functionName, parser, result);
                         // DO NOT FORGET TO EXECUTE THE THREAD
                         thread.start();
                         // ... wait until termination
                         System.out.println(result.get());
                         // -----------------------------------
                         // "fieldToModify" IN "FunctionFunction" WILL BE:
                         // Javinator9889
                         // System.out.: Javinator9889
                     }
                     
                 
        Parameters:
        function - function that follows the implementation described at the full documentation.
        args - arguments that receive that function.
        result - AtomicReference that will contain the function result.
        See Also:
        ArgumentParser, AtomicReference
      • run

        public void run()
        If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns. When finishes, it calls subscribed classes notifying that it has just ended-up.

        Subclasses of Thread should override this method.

        Specified by:
        run in interface java.lang.Runnable
        Overrides:
        run in class java.lang.Thread
        See Also:
        Thread.start(), Thread.stop(), NotifyingThread(ThreadGroup, Runnable, String)
      • uncaughtException

        public void uncaughtException​(@NotNull
                                      java.lang.Thread thread,
                                      @NotNull
                                      java.lang.Throwable exception)
        Method invoked when the given thread terminates due to the given uncaught exception.

        Any exception thrown by this method will be ignored by the Java Virtual Machine.

        Specified by:
        uncaughtException in interface java.lang.Thread.UncaughtExceptionHandler
        Parameters:
        thread - the thread
        exception - the exception
      • toString

        public java.lang.String toString()
        Returns a string representation of this thread, including the thread's name, priority, and thread group.
        Overrides:
        toString in class java.lang.Thread
        Returns:
        a string representation of this thread.
      • equals

        public boolean equals​(java.lang.Object obj)
        Indicates whether some other object is "equal to" this one.

        The equals method implements an equivalence relation on non-null object references:

        • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
        • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
        • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
        • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
        • For any non-null reference value x, x.equals(null) should return false.

        The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

        Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

        Overrides:
        equals in class java.lang.Object
        Parameters:
        obj - the reference object with which to compare.
        Returns:
        true if this object is the same as the obj argument; false otherwise.
        See Also:
        hashCode(), HashMap
      • hashCode

        public int hashCode()
        Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.

        The general contract of hashCode is:

        • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
        • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
        • It is not required that if two objects are unequal according to the Object.equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

        As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (The hashCode may or may not be implemented as some function of an object's memory address at some point in time.)

        Overrides:
        hashCode in class java.lang.Object
        Returns:
        a hash code value for this object.
        See Also:
        Object.equals(java.lang.Object), System.identityHashCode(java.lang.Object)
      • clone

        protected java.lang.Object clone()
                                  throws java.lang.CloneNotSupportedException
        Throws CloneNotSupportedException as a Thread can not be meaningfully cloned. Construct a new Thread instead.
        Overrides:
        clone in class java.lang.Thread
        Throws:
        java.lang.CloneNotSupportedException - always