Alachisoft.NCache.Common.Threading.Promise Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of nc-common Show documentation
Show all versions of nc-common Show documentation
Internal package of Alachisoft.
package Alachisoft.NCache.Common.Threading;
/**
* The caller may choose to check for the result at a later time, or immediately and it may block or not. Both the caller and responder have to know the promise.
*
*
* Allows a thread to submit an asynchronous request and to wait for the result.
Author: Chris Koiak, Bela Ban
Date: 12/03/2003
*/
public class Promise {
/**
* The result of the request
*/
private Object _result = null;
/**
* Used to wait on the result
*/
private Object _mutex = new Object();
/**
* If result was already submitted, returns it immediately, else blocks until results becomes available. *
*
* @param timeout Maximum time to wait for result.
* @return Promise result
*/
public final Object WaitResult(long timeout) {
Object ret = null;
synchronized (_mutex) {
if (_result != null) {
ret = _result;
_result = null;
return ret;
}
if (timeout <= 0) {
try {
Monitor.wait(_mutex); //_mutex.wait();
} catch (java.lang.InterruptedException ex) {
//Basit: Should use NCacheLogs
//Trace.error("Promise.WaitResult", "exception=" + ex.toString());
}
} else {
try {
Monitor.wait(_mutex, timeout);// _mutex.wait(timeout);
} catch (java.lang.InterruptedException ex) {
//Basit: Should use NCacheLogs
//Trace.error("Promise.WaitResult:", "exception=" + ex.toString());
}
}
// SAL: Cosider Trace
if (_result != null) {
ret = _result;
_result = null;
return ret;
}
return null;
}
}
/**
* Checks whether result is available. Does not block.
*
* @return Result if available
*/
public final Object getIsResultAvailable() {
synchronized (_mutex) {
return _result;
}
}
/**
* Sets the result and notifies any threads waiting for it
*
* @param obj Result of request
*/
public final void SetResult(Object obj) {
synchronized (_mutex) {
_result = obj;
Monitor.pulse(_mutex); //_mutex.notifyAll();
}
}
/**
* Clears the result and causes all waiting threads to return
*/
public final void Reset() {
synchronized (_mutex) {
_result = null;
Monitor.pulse(_mutex);//_mutex.notifyAll();
}
}
/**
* String representation of the result
*
* @return String representation of the result
*/
@Override
public String toString() {
return "result=" + _result;
}
}