Class NotifyingThread
- java.lang.Object
-
- java.lang.Thread
-
- com.github.javinator9889.threading.threads.notifyingthread.NotifyingThread
-
- All Implemented Interfaces:
java.lang.Runnable,java.lang.Thread.UncaughtExceptionHandler
public class NotifyingThread extends java.lang.Thread implements java.lang.Thread.UncaughtExceptionHandlerNotifyingThreadprovides an specialised class on threading that adds more options to the current available threading models:-
Notifying: sometimes we want to get notified when a
Threadcompletes its execution, but the most we can do is just wait until its completion for going to the next step in our execution.NotifyingThreadprovides a fast, powerful class for getting notified when threads we want finish, just by subscribing to the listener classes implementing theOnThreadCompletedListenerinterface. -
Fast development: it is very common that we declare the
following:
With// 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(); }NotifyingThreadis 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:
NotifyingThreadprovides adaptive methods for setting up the executables, so you can use Consumer, Function, Runnable and Supplier.
Thread.UncaughtExceptionHandlerfor notifying subscribed classes that the thread has finished with an exception. If you want to use yours, just setup theUncaughtExceptionHandlerwithThread.setUncaughtExceptionHandler(UncaughtExceptionHandler).In addition, this class supports async calling for subscribed classes when the threads finishes. Refer to async execution docs for more information.
-
-
Field Summary
Fields Modifier and Type Field Description static intDEFAULT_CAPACITYDefault capacity of subscribed classes - normally, we only want one class to get notified when a thread completes.private java.util.concurrent.atomic.AtomicBooleanmShouldCallSubscribedClassesAsynchronouslyWhether the calling of subscribed classes must be done asynchronously or not.private java.util.ArrayList<OnThreadCompletedListener>mSubscribedClassesListof subscribed classes.private java.lang.RunnablemTargetTarget that will be executed whenThread.start()is called.private static java.util.concurrent.atomic.AtomicIntegermThreadNumberThread count number.static java.lang.StringTHREAD_PREFIXThread prefix used when invoking "toString".
-
Constructor Summary
Constructors Constructor Description NotifyingThread()Allocates a newThreadobject.NotifyingThread(OnThreadCompletedListener... listeners)Allocates a newThreadobject.NotifyingThread(java.lang.Runnable target)Allocates a newThreadobject.NotifyingThread(java.lang.Runnable target, OnThreadCompletedListener... listeners)Allocates a newThreadobject.NotifyingThread(java.lang.Runnable target, java.lang.String name)Allocates a newThreadobject.NotifyingThread(java.lang.Runnable target, java.lang.String name, OnThreadCompletedListener... listeners)Allocates a newThreadobject.NotifyingThread(java.lang.String name)Allocates a newThreadobject.NotifyingThread(java.lang.String name, OnThreadCompletedListener... listeners)Allocates a newThreadobject.NotifyingThread(java.lang.ThreadGroup group, java.lang.Runnable target)Allocates a newThreadobject.NotifyingThread(java.lang.ThreadGroup group, java.lang.Runnable target, OnThreadCompletedListener... listeners)Allocates a newThreadobject.NotifyingThread(java.lang.ThreadGroup group, java.lang.Runnable target, java.lang.String name)Allocates a newThreadobject so that it hastargetas its run object, has the specifiednameas its name, and belongs to the thread group referred to bygroup.NotifyingThread(java.lang.ThreadGroup group, java.lang.Runnable target, java.lang.String name, long stackSize)Allocates a newThreadobject so that it hastargetas its run object, has the specifiednameas its name, and belongs to the thread group referred to bygroup, 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 newThreadobject so that it hastargetas its run object, has the specifiednameas its name, and belongs to the thread group referred to bygroup, and has the specified stack size.NotifyingThread(java.lang.ThreadGroup group, java.lang.Runnable target, java.lang.String name, OnThreadCompletedListener... listeners)Allocates a newThreadobject so that it hastargetas its run object, has the specifiednameas its name, and belongs to the thread group referred to bygroup.NotifyingThread(java.lang.ThreadGroup group, java.lang.String name)Allocates a newThreadobject.NotifyingThread(java.lang.ThreadGroup group, java.lang.String name, OnThreadCompletedListener... listeners)Allocates a newThreadobject.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidaddOnThreadCompletedListener(OnThreadCompletedListener listener)Adds a new listener to the list of subscribed classes.voidaddOnThreadCompleteListener(OnThreadCompletedListener... listeners)Adds new listeners to the list of subscribed classes at once.private voidcallSubscribedClasses(java.lang.Thread thread, java.lang.Throwable exception)When athreadfinishes, or an exception is thrown, this method is called byrun()oruncaughtException(Thread, Throwable), the first one to occur.protected java.lang.Objectclone()Throws CloneNotSupportedException as a Thread can not be meaningfully cloned.booleanequals(java.lang.Object obj)Indicates whether some other object is "equal to" this one.inthashCode()Returns a hash code value for the object.private static intnextThreadNumber()Returns the corresponding thread number for a newly createdNotifyingThread.voidremoveAllListeners()Un-subscribes all classes listening to this thread completion.booleanremoveOnThreadCompletedListener(OnThreadCompletedListener listener)Tries to remove the givenlistenerfrom the list of subscribed classes, if present.voidrun()If this thread was constructed using a separateRunnablerun object, then thatRunnableobject'srunmethod is called; otherwise, this method does nothing and returns.voidsetExecutable(java.lang.Runnable runnable)Once after theNotifyingThreadis created, this method can be used for setting theRunnablethat will be executed whenThread.start()is called.voidsetExecutable(java.util.function.Consumer<ArgumentParser> consumer, ArgumentParser args)Once after theNotifyingThreadis created, this method can be used for setting theRunnablethat will be executed whenThread.start()is called.voidsetExecutable(java.util.function.Function<ArgumentParser,?> function, ArgumentParser args, java.util.concurrent.atomic.AtomicReference result)Once after theNotifyingThreadis created, this method can be used for setting theRunnablethat will be executed whenThread.start()is called.voidsetExecutable(java.util.function.Supplier supplier, java.util.concurrent.atomic.AtomicReference result)Once after theNotifyingThreadis created, this method can be used for setting theRunnablethat will be executed whenThread.start()is called.voidsetShouldCallSubscribedClassesAsynchronously(boolean shouldCallAsynchronously)When passingtrueto this method, whenrun()finishes and subscribed classes are called, that call will be done on a new asynchronous thread.java.lang.StringtoString()Returns a string representation of this thread, including the thread's name, priority, and thread group.voiduncaughtException(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
-
-
-
-
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.
-
mSubscribedClasses
private java.util.ArrayList<OnThreadCompletedListener> mSubscribedClasses
Listof subscribed classes.- See Also:
OnThreadCompletedListener
-
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 whenThread.start()is called.
-
-
Constructor Detail
-
NotifyingThread
public NotifyingThread()
Allocates a newThreadobject. This constructor has the same effect as NotifyingThread(null, null, gname), wheregnameis a newly generated name. Automatically generated names are of the form"NotifyingThread-"+n, where n is an integer.
-
NotifyingThread
public NotifyingThread(@NotNull OnThreadCompletedListener... listeners)Allocates a newThreadobject. This constructor has the same effect as NotifyingThread(null, null, gname), wheregnameis a newly generated name. Automatically generated names are of the form"NotifyingThread-"+n, where n is an integer.- Parameters:
listeners- anarrayof listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at theOnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable)method, giving bothRunnableof the just finished thread andThrowablewith any exception that occurred during execution.
-
NotifyingThread
public NotifyingThread(java.lang.Runnable target)
Allocates a newThreadobject. This constructor has the same effect as NotifyingThread(null, target, gname), wheregnameis a newly generated name. Automatically generated names are of the form"NotifyingThread-"+n, where n is an integer.- Parameters:
target- the object whoserunmethod is invoked when this thread is started. Ifnull, this classesrunmethod does nothing.
-
NotifyingThread
public NotifyingThread(java.lang.Runnable target, @NotNull OnThreadCompletedListener... listeners)Allocates a newThreadobject. This constructor has the same effect as NotifyingThread(null, target, gname, listeners), wheregnameis a newly generated name. Automatically generated names are of the form"NotifyingThread-"+n, where n is an integer.- Parameters:
target- the object whoserunmethod is invoked when this thread is started. Ifnull, this classesrunmethod does nothing.listeners- anarrayof listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at theOnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable)method, giving bothRunnableof the just finished thread andThrowablewith any exception that occurred during execution.
-
NotifyingThread
public NotifyingThread(@Nullable java.lang.ThreadGroup group, java.lang.Runnable target)Allocates a newThreadobject. This constructor has the same effect as NotifyingThread(group, target, gname), wheregnameis a newly generated name. Automatically generated names are of the form"NotifyingThread-"+n, where n is an integer.- Parameters:
group- the thread group. Ifnulland there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager orSecurityManager.getThreadGroup()returnsnull, the group is set to the current thread's thread group.target- the object whoserunmethod is invoked when this thread is started. Ifnull, 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 newThreadobject. This constructor has the same effect as NotifyingThread(group, target, gname, listeners), wheregnameis a newly generated name. Automatically generated names are of the form"NotifyingThread-"+n, where n is an integer.- Parameters:
group- the thread group. Ifnulland there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager orSecurityManager.getThreadGroup()returnsnull, the group is set to the current thread's thread group.target- the object whoserunmethod is invoked when this thread is started. Ifnull, this thread's run method is invoked.listeners- anarrayof listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at theOnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable)method, giving bothRunnableof the just finished thread andThrowablewith 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, @NotNull OnThreadCompletedListener... listeners)Allocates a newThreadobject. This constructor has the same effect as NotifyingThread(null, null, name, listeners).- Parameters:
name- the name of the new thread.listeners- anarrayof listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at theOnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable)method, giving bothRunnableof the just finished thread andThrowablewith any exception that occurred during execution.
-
NotifyingThread
public NotifyingThread(@Nullable java.lang.ThreadGroup group, @NotNull java.lang.String name, @NotNull OnThreadCompletedListener... listeners)Allocates a newThreadobject. This constructor has the same effect as NotifyingThread(group, null, name, listeners).- Parameters:
group- the thread group. Ifnulland there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager orSecurityManager.getThreadGroup()returnsnull, the group is set to the current thread's thread group.name- the name of the new thread.listeners- anarrayof listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at theOnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable)method, giving bothRunnableof the just finished thread andThrowablewith 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 newThreadobject. 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 newThreadobject. This constructor has the same effect as NotifyingThread(null, target, name, listeners).- Parameters:
target- the object whoserunmethod is invoked when this thread is started. Ifnull, this thread's run method is invoked.name- the name of the new thread.listeners- anarrayof listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at theOnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable)method, giving bothRunnableof the just finished thread andThrowablewith any exception that occurred during execution.
-
NotifyingThread
public NotifyingThread(@Nullable java.lang.ThreadGroup group, @NotNull java.lang.String name)Allocates a newThreadobject. This constructor has the same effect as NotifyingThread(group, null, name).- Parameters:
group- the thread group. Ifnulland there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager orSecurityManager.getThreadGroup()returnsnull, 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 newThreadobject so that it hastargetas its run object, has the specifiednameas its name, and belongs to the thread group referred to bygroup.If there is a security manager, its
checkAccessmethod is invoked with the ThreadGroup as its argument.In addition, its
checkPermissionmethod is invoked with theRuntimePermission("enableContextClassLoaderOverride")permission when invoked directly or indirectly by the constructor of a subclass which overrides thegetContextClassLoaderorsetContextClassLoadermethods.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. Ifnulland there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager orSecurityManager.getThreadGroup()returnsnull, the group is set to the current thread's thread group.target- the object whoserunmethod is invoked when this thread is started. Ifnull, this thread's run method is invoked.name- the name of the new thread.listeners- anarrayof listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at theOnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable)method, giving bothRunnableof the just finished thread andThrowablewith 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 newThreadobject. This constructor has the same effect as NotifyingThread(null, target, name).- Parameters:
target- the object whoserunmethod is invoked when this thread is started. Ifnull, 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 newThreadobject so that it hastargetas its run object, has the specifiednameas its name, and belongs to the thread group referred to bygroup.If there is a security manager, its
checkAccessmethod is invoked with the ThreadGroup as its argument.In addition, its
checkPermissionmethod is invoked with theRuntimePermission("enableContextClassLoaderOverride")permission when invoked directly or indirectly by the constructor of a subclass which overrides thegetContextClassLoaderorsetContextClassLoadermethods.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. Ifnulland there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager orSecurityManager.getThreadGroup()returnsnull, the group is set to the current thread's thread group.target- the object whoserunmethod is invoked when this thread is started. Ifnull, 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 newThreadobject so that it hastargetas its run object, has the specifiednameas its name, and belongs to the thread group referred to bygroup, 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 thestackSizeparameter, if any, is highly platform dependent.On some platforms, specifying a higher value for the
stackSizeparameter may allow a thread to achieve greater recursion depth before throwing aStackOverflowError. Similarly, specifying a lower value may allow a greater number of threads to exist concurrently without throwing anOutOfMemoryError(or other internal error). The details of the relationship between the value of thestackSizeparameter and the maximum recursion depth and concurrency level are platform-dependent. On some platforms, the value of thestackSizeparameter may have no effect whatsoever.The virtual machine is free to treat the
stackSizeparameter 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
stackSizeparameter will cause this constructor to behave exactly like theThread(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
stackSizeparameter.- Parameters:
group- the thread group. Ifnulland there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager orSecurityManager.getThreadGroup()returnsnull, the group is set to the current thread's thread group.target- the object whoserunmethod is invoked when this thread is started. Ifnull, 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 newThreadobject so that it hastargetas its run object, has the specifiednameas its name, and belongs to the thread group referred to bygroup, 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 thestackSizeparameter, if any, is highly platform dependent.On some platforms, specifying a higher value for the
stackSizeparameter may allow a thread to achieve greater recursion depth before throwing aStackOverflowError. Similarly, specifying a lower value may allow a greater number of threads to exist concurrently without throwing anOutOfMemoryError(or other internal error). The details of the relationship between the value of thestackSizeparameter and the maximum recursion depth and concurrency level are platform-dependent. On some platforms, the value of thestackSizeparameter may have no effect whatsoever.The virtual machine is free to treat the
stackSizeparameter 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
stackSizeparameter will cause this constructor to behave exactly like theThread(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
stackSizeparameter.- Parameters:
group- the thread group. Ifnulland there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager orSecurityManager.getThreadGroup()returnsnull, the group is set to the current thread's thread group.target- the object whoserunmethod is invoked when this thread is started. Ifnull, 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- anarrayof listeners which are classes that implements OnThreadCompletedListener, so when a thread finish its work, those classes are called at theOnThreadCompletedListener.onThreadCompletedListener(Thread, Throwable)method, giving bothRunnableof the just finished thread andThrowablewith 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 createdNotifyingThread.- Returns:
intwith the thread number.
-
callSubscribedClasses
private void callSubscribedClasses(@NotNull java.lang.Thread thread, @Nullable java.lang.Throwable exception)When athreadfinishes, or an exception is thrown, this method is called byrun()oruncaughtException(Thread, Throwable), the first one to occur.This method has the following behaviour:
- If there is no subscribed class, it immediately finishes.
-
If async
mode is set-up (it is
true), each subscribed class is called on a new thread for not blocking main thread doing the calls. - On the other hand, if async mode is off, each subscribed class is called on the main thread, being possible not calling all classes if any exception occurs.
- Parameters:
thread- thread that has just finished its execution (because of an exception or finished normally).exception- exception thrown by the thread execution - it will benullif no exception has been thrown.- See Also:
-
setShouldCallSubscribedClassesAsynchronously(boolean),addOnThreadCompletedListener(OnThreadCompletedListener),addOnThreadCompleteListener(OnThreadCompletedListener...)
-
setShouldCallSubscribedClassesAsynchronously
public void setShouldCallSubscribedClassesAsynchronously(boolean shouldCallAsynchronously)
When passingtrueto this method, whenrun()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.
-
Threadis not blocked, so it can resume any execution or get immediatelyidlein aThreadPoolExecutor.
- 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.
-
addOnThreadCompletedListener
public void addOnThreadCompletedListener(@NotNull OnThreadCompletedListener listener)Adds a new listener to the list of subscribed classes. For adding more than one thread at once, please refer toaddOnThreadCompleteListener(OnThreadCompletedListener...).- Parameters:
listener- new listener that will be called on this thread completion.
-
addOnThreadCompleteListener
public void addOnThreadCompleteListener(@NotNull OnThreadCompletedListener... listeners)Adds new listeners to the list of subscribed classes at once. For adding just one listener, please refer toaddOnThreadCompletedListener(OnThreadCompletedListener).- Parameters:
listeners-arrayof listeners that will be called on this thread completion.
-
removeOnThreadCompletedListener
public boolean removeOnThreadCompletedListener(@NotNull OnThreadCompletedListener listener)Tries to remove the givenlistenerfrom the list of subscribed classes, if present.- Parameters:
listener- class to remove.- Returns:
truewhen the item was present,falseif 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 theNotifyingThreadis created, this method can be used for setting theRunnablethat will be executed whenThread.start()is called.This class uses a
Consumer, which is a type ofFunctionwhich accepts one parameter and produces no output. They arevoidfunctions.The function that will be inside this declaration must follow the following syntax:
That function will apply a// 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); }Consumerfunction, 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 theNotifyingThreadis created, this method can be used for setting theRunnablethat will be executed whenThread.start()is called.This class uses a
Runnable, which is a type ofFunctionwhich accepts no parameters and produces no output. They arevoidfunctions.The function that will be inside this declaration must follow the following syntax:
That function will apply a// Class name: RunnableFunction public void functionName() { // Useful for working with class fields once an operation is completed. this.fieldToModify = "Javinator9889"; }Runnablefunction, 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 theNotifyingThreadis created, this method can be used for setting theRunnablethat will be executed whenThread.start()is called.This class uses a
Supplier, which is a type ofFunctionwhich accepts no parameters and produces an output. Also, this type of functions are very similar toFuture.The function that will be inside this declaration must follow the following syntax:
That function will apply a// Class name: SupplierFunction public int functionName() { // Produce some result/attribute with the class fields' return this.fieldToProduce; }Supplierfunction, 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-AtomicReferencethat 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 theNotifyingThreadis created, this method can be used for setting theRunnablethat will be executed whenThread.start()is called.This class uses a
Function, which is a type ofFunctionwhich accepts one parameter and produces one output. They are very similar toFuture, 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:
That function will apply a// 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; }Functionfunction, 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-AtomicReferencethat will contain the function result.- See Also:
ArgumentParser,AtomicReference
-
run
public void run()
If this thread was constructed using a separateRunnablerun object, then thatRunnableobject'srunmethod is called; otherwise, this method does nothing and returns. When finishes, it callssubscribed classesnotifying that it has just ended-up.Subclasses of
Threadshould override this method.- Specified by:
runin interfacejava.lang.Runnable- Overrides:
runin classjava.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:
uncaughtExceptionin interfacejava.lang.Thread.UncaughtExceptionHandler- Parameters:
thread- the threadexception- 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:
toStringin classjava.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
equalsmethod implements an equivalence relation on non-null object references:- It is reflexive: for any non-null
reference value
x,x.equals(x)should returntrue. - It is symmetric: for any non-null
reference values
xandy,x.equals(y)should returntrueif and only ify.equals(x)returnstrue. - It is transitive: for any non-null
reference values
x,y, andz, ifx.equals(y)returnstrueandy.equals(z)returnstrue, thenx.equals(z)should returntrue. - It is consistent: for any non-null
reference values
xandy, multiple invocations ofx.equals(y)consistently returntrueor consistently returnfalse, provided no information used inequalscomparisons on the objects is modified. - For any non-null reference value
x,x.equals(null)should returnfalse.
The
equalsmethod for classObjectimplements the most discriminating possible equivalence relation on objects; that is, for any non-null reference valuesxandy, this method returnstrueif and only ifxandyrefer to the same object (x == yhas the valuetrue).Note that it is generally necessary to override the
hashCodemethod whenever this method is overridden, so as to maintain the general contract for thehashCodemethod, which states that equal objects must have equal hash codes.- Overrides:
equalsin classjava.lang.Object- Parameters:
obj- the reference object with which to compare.- Returns:
trueif this object is the same as the obj argument;falseotherwise.- See Also:
hashCode(),HashMap
- It is reflexive: for any non-null
reference value
-
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 byHashMap.The general contract of
hashCodeis:- Whenever it is invoked on the same object more
than once during
an execution of a Java application, the
hashCodemethod must consistently return the same integer, provided no information used inequalscomparisons 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 thehashCodemethod 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 thehashCodemethod 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
Objectdoes 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:
hashCodein classjava.lang.Object- Returns:
- a hash code value for this object.
- See Also:
Object.equals(java.lang.Object),System.identityHashCode(java.lang.Object)
- Whenever it is invoked on the same object more
than once during
an execution of a Java application, the
-
clone
protected java.lang.Object clone() throws java.lang.CloneNotSupportedExceptionThrows CloneNotSupportedException as a Thread can not be meaningfully cloned. Construct a new Thread instead.- Overrides:
clonein classjava.lang.Thread- Throws:
java.lang.CloneNotSupportedException- always
-
-