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.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 theOnThreadCompletedListener
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(); }
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.
Thread.UncaughtExceptionHandler
for notifying subscribed classes that the thread has finished with an exception. If you want to use yours, just setup theUncaughtExceptionHandler
withThread.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 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 whenThread.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".
-
Constructor Summary
Constructors Constructor Description NotifyingThread()
Allocates a newThread
object.NotifyingThread(OnThreadCompletedListener... listeners)
Allocates a newThread
object.NotifyingThread(java.lang.Runnable target)
Allocates a newThread
object.NotifyingThread(java.lang.Runnable target, OnThreadCompletedListener... listeners)
Allocates a newThread
object.NotifyingThread(java.lang.Runnable target, java.lang.String name)
Allocates a newThread
object.NotifyingThread(java.lang.Runnable target, java.lang.String name, OnThreadCompletedListener... listeners)
Allocates a newThread
object.NotifyingThread(java.lang.String name)
Allocates a newThread
object.NotifyingThread(java.lang.String name, OnThreadCompletedListener... listeners)
Allocates a newThread
object.NotifyingThread(java.lang.ThreadGroup group, java.lang.Runnable target)
Allocates a newThread
object.NotifyingThread(java.lang.ThreadGroup group, java.lang.Runnable target, OnThreadCompletedListener... listeners)
Allocates a newThread
object.NotifyingThread(java.lang.ThreadGroup group, java.lang.Runnable target, java.lang.String name)
Allocates a newThread
object so that it hastarget
as its run object, has the specifiedname
as 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 newThread
object so that it hastarget
as its run object, has the specifiedname
as 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 newThread
object so that it hastarget
as its run object, has the specifiedname
as 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 newThread
object so that it hastarget
as its run object, has the specifiedname
as its name, and belongs to the thread group referred to bygroup
.NotifyingThread(java.lang.ThreadGroup group, java.lang.String name)
Allocates a newThread
object.NotifyingThread(java.lang.ThreadGroup group, java.lang.String name, OnThreadCompletedListener... listeners)
Allocates a newThread
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 athread
finishes, or an exception is thrown, this method is called byrun()
oruncaughtException(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 createdNotifyingThread
.void
removeAllListeners()
Un-subscribes all classes listening to this thread completion.boolean
removeOnThreadCompletedListener(OnThreadCompletedListener listener)
Tries to remove the givenlistener
from the list of subscribed classes, if present.void
run()
If this thread was constructed using a separateRunnable
run object, then thatRunnable
object'srun
method is called; otherwise, this method does nothing and returns.void
setExecutable(java.lang.Runnable runnable)
Once after theNotifyingThread
is created, this method can be used for setting theRunnable
that will be executed whenThread.start()
is called.void
setExecutable(java.util.function.Consumer<ArgumentParser> consumer, ArgumentParser args)
Once after theNotifyingThread
is created, this method can be used for setting theRunnable
that will be executed whenThread.start()
is called.void
setExecutable(java.util.function.Function<ArgumentParser,?> function, ArgumentParser args, java.util.concurrent.atomic.AtomicReference result)
Once after theNotifyingThread
is created, this method can be used for setting theRunnable
that will be executed whenThread.start()
is called.void
setExecutable(java.util.function.Supplier supplier, java.util.concurrent.atomic.AtomicReference result)
Once after theNotifyingThread
is created, this method can be used for setting theRunnable
that will be executed whenThread.start()
is called.void
setShouldCallSubscribedClassesAsynchronously(boolean shouldCallAsynchronously)
When passingtrue
to this method, whenrun()
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
-
-
-
-
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
List
of 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 newThread
object. This constructor has the same effect as NotifyingThread(null, null, gname)
, wheregname
is 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 newThread
object. This constructor has the same effect as NotifyingThread(null, null, gname)
, wheregname
is a newly generated name. Automatically generated names are of the form"NotifyingThread-"+
n, where n is an integer.- Parameters:
listeners
- anarray
of 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 bothRunnable
of the just finished thread andThrowable
with any exception that occurred during execution.
-
NotifyingThread
public NotifyingThread(java.lang.Runnable target)
Allocates a newThread
object. This constructor has the same effect as NotifyingThread(null, target, gname)
, wheregname
is a newly generated name. Automatically generated names are of the form"NotifyingThread-"+
n, where n is an integer.- Parameters:
target
- the object whoserun
method is invoked when this thread is started. Ifnull
, this classesrun
method does nothing.
-
NotifyingThread
public NotifyingThread(java.lang.Runnable target, @NotNull OnThreadCompletedListener... listeners)
Allocates a newThread
object. This constructor has the same effect as NotifyingThread(null, target, gname, listeners)
, wheregname
is a newly generated name. Automatically generated names are of the form"NotifyingThread-"+
n, where n is an integer.- Parameters:
target
- the object whoserun
method is invoked when this thread is started. Ifnull
, this classesrun
method does nothing.listeners
- anarray
of 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 bothRunnable
of the just finished thread andThrowable
with any exception that occurred during execution.
-
NotifyingThread
public NotifyingThread(@Nullable java.lang.ThreadGroup group, java.lang.Runnable target)
Allocates a newThread
object. This constructor has the same effect as NotifyingThread(group, target, gname)
, wheregname
is a newly generated name. Automatically generated names are of the form"NotifyingThread-"+
n, where n is an integer.- Parameters:
group
- the thread group. Ifnull
and 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 whoserun
method 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 newThread
object. This constructor has the same effect as NotifyingThread(group, target, gname, listeners)
, wheregname
is a newly generated name. Automatically generated names are of the form"NotifyingThread-"+
n, where n is an integer.- Parameters:
group
- the thread group. Ifnull
and 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 whoserun
method is invoked when this thread is started. Ifnull
, this thread's run method is invoked.listeners
- anarray
of 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 bothRunnable
of the just finished thread andThrowable
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, @NotNull OnThreadCompletedListener... listeners)
Allocates a newThread
object. This constructor has the same effect as NotifyingThread(null, null, name, listeners)
.- Parameters:
name
- the name of the new thread.listeners
- anarray
of 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 bothRunnable
of the just finished thread andThrowable
with any exception that occurred during execution.
-
NotifyingThread
public NotifyingThread(@Nullable java.lang.ThreadGroup group, @NotNull java.lang.String name, @NotNull OnThreadCompletedListener... listeners)
Allocates a newThread
object. This constructor has the same effect as NotifyingThread(group, null, name, listeners)
.- Parameters:
group
- the thread group. Ifnull
and 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
- anarray
of 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 bothRunnable
of the just finished thread andThrowable
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 newThread
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 newThread
object. This constructor has the same effect as NotifyingThread(null, target, name, listeners)
.- Parameters:
target
- the object whoserun
method is invoked when this thread is started. Ifnull
, this thread's run method is invoked.name
- the name of the new thread.listeners
- anarray
of 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 bothRunnable
of the just finished thread andThrowable
with any exception that occurred during execution.
-
NotifyingThread
public NotifyingThread(@Nullable java.lang.ThreadGroup group, @NotNull java.lang.String name)
Allocates a newThread
object. This constructor has the same effect as NotifyingThread(group, null, name)
.- Parameters:
group
- the thread group. Ifnull
and 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 newThread
object so that it hastarget
as its run object, has the specifiedname
as its name, and belongs to the thread group referred to bygroup
.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 theRuntimePermission("enableContextClassLoaderOverride")
permission when invoked directly or indirectly by the constructor of a subclass which overrides thegetContextClassLoader
orsetContextClassLoader
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. Ifnull
and 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 whoserun
method is invoked when this thread is started. Ifnull
, this thread's run method is invoked.name
- the name of the new thread.listeners
- anarray
of 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 bothRunnable
of the just finished thread andThrowable
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 newThread
object. This constructor has the same effect as NotifyingThread(null, target, name)
.- Parameters:
target
- the object whoserun
method 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 newThread
object so that it hastarget
as its run object, has the specifiedname
as its name, and belongs to the thread group referred to bygroup
.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 theRuntimePermission("enableContextClassLoaderOverride")
permission when invoked directly or indirectly by the constructor of a subclass which overrides thegetContextClassLoader
orsetContextClassLoader
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. Ifnull
and 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 whoserun
method 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 newThread
object so that it hastarget
as its run object, has the specifiedname
as 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 thestackSize
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 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 thestackSize
parameter and the maximum recursion depth and concurrency level are platform-dependent. On some platforms, the value of thestackSize
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 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
stackSize
parameter.- Parameters:
group
- the thread group. Ifnull
and 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 whoserun
method 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 newThread
object so that it hastarget
as its run object, has the specifiedname
as 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 thestackSize
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 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 thestackSize
parameter and the maximum recursion depth and concurrency level are platform-dependent. On some platforms, the value of thestackSize
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 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
stackSize
parameter.- Parameters:
group
- the thread group. Ifnull
and 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 whoserun
method 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
- anarray
of 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 bothRunnable
of the just finished thread andThrowable
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 createdNotifyingThread
.- Returns:
int
with the thread number.
-
callSubscribedClasses
private void callSubscribedClasses(@NotNull java.lang.Thread thread, @Nullable java.lang.Throwable exception)
When athread
finishes, 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 benull
if no exception has been thrown.- See Also:
-
setShouldCallSubscribedClassesAsynchronously(boolean)
,addOnThreadCompletedListener(OnThreadCompletedListener)
,addOnThreadCompleteListener(OnThreadCompletedListener...)
-
setShouldCallSubscribedClassesAsynchronously
public void setShouldCallSubscribedClassesAsynchronously(boolean shouldCallAsynchronously)
When passingtrue
to 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.
-
Thread
is not blocked, so it can resume any execution or get immediatelyidle
in 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
-array
of listeners that will be called on this thread completion.
-
removeOnThreadCompletedListener
public boolean removeOnThreadCompletedListener(@NotNull OnThreadCompletedListener listener)
Tries to remove the givenlistener
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 theNotifyingThread
is created, this method can be used for setting theRunnable
that will be executed whenThread.start()
is called.This class uses a
Consumer
, which is a type ofFunction
which accepts one parameter and produces no output. They arevoid
functions.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); }
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 theNotifyingThread
is created, this method can be used for setting theRunnable
that will be executed whenThread.start()
is called.This class uses a
Runnable
, which is a type ofFunction
which accepts no parameters and produces no output. They arevoid
functions.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"; }
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 theNotifyingThread
is created, this method can be used for setting theRunnable
that will be executed whenThread.start()
is called.This class uses a
Supplier
, which is a type ofFunction
which 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; }
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 theNotifyingThread
is created, this method can be used for setting theRunnable
that will be executed whenThread.start()
is called.This class uses a
Function
, which is a type ofFunction
which 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; }
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 separateRunnable
run object, then thatRunnable
object'srun
method is called; otherwise, this method does nothing and returns. When finishes, it callssubscribed classes
notifying that it has just ended-up.Subclasses of
Thread
should override this method.- Specified by:
run
in interfacejava.lang.Runnable
- Overrides:
run
in 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:
uncaughtException
in 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:
toString
in 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
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 returntrue
. - It is symmetric: for any non-null
reference values
x
andy
,x.equals(y)
should returntrue
if and only ify.equals(x)
returnstrue
. - It is transitive: for any non-null
reference values
x
,y
, andz
, ifx.equals(y)
returnstrue
andy.equals(z)
returnstrue
, thenx.equals(z)
should returntrue
. - It is consistent: for any non-null
reference values
x
andy
, multiple invocations ofx.equals(y)
consistently returntrue
or consistently returnfalse
, provided no information used inequals
comparisons on the objects is modified. - For any non-null reference value
x
,x.equals(null)
should returnfalse
.
The
equals
method for classObject
implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference valuesx
andy
, this method returnstrue
if and only ifx
andy
refer to the same object (x == y
has the valuetrue
).Note that it is generally necessary to override the
hashCode
method whenever this method is overridden, so as to maintain the general contract for thehashCode
method, which states that equal objects must have equal hash codes.- Overrides:
equals
in classjava.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
- 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
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 inequals
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 thehashCode
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 thehashCode
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 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.CloneNotSupportedException
Throws CloneNotSupportedException as a Thread can not be meaningfully cloned. Construct a new Thread instead.- Overrides:
clone
in classjava.lang.Thread
- Throws:
java.lang.CloneNotSupportedException
- always
-
-