software.nealk.concurrent.tasks.RetrievableTask Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of nealk-sdk-concurrent-lib Show documentation
Show all versions of nealk-sdk-concurrent-lib Show documentation
An easy-to-consume concurrency library allowing for "Tasks" to execute business logic in a thread safe manner. This library helps users achieve multi-threading in their applications without worrying about synchronization and blocking for race conditions.
The newest version!
package software.nealk.concurrent.tasks;
import software.nealk.concurrent.Task;
import software.nealk.concurrent.ThreadSafe;
public abstract class RetrievableTask implements Task{
protected volatile T obj;
private java.util.concurrent.Semaphore objSem;
protected RetrievableTask(){
this.objSem = new java.util.concurrent.Semaphore(0, false);
}
@Override
public final void run() {
System.out.println("Thread "
+ Thread.currentThread().getId()
+ " is running....");
this.execute();
this.objSem.release();
}
protected abstract void execute();
/**
* Blocks until {@link obj} of type <T> is not null. Returns the {@link obj}.
*
* Note that compile-time type checking is enabled. The usage
* of Java Generics nullifies the compiler warning "unchecked".
*/
@SuppressWarnings("unchecked")
@Override
@ThreadSafe
public final T getVal() throws InterruptedException {
this.objSem.acquire();
return obj;
}
}