T
- the generic type of this classpublic abstract class ForkInvoker<T> extends Object
#invoke(T)
into calls to #fork(T)
or #call(T)
depending on the max number of reentrant calls to #invoke(T)
.
This class prevents StackOverflowError
s in case of methods that end up invoking themselves,
such is common for Callback.completed(Object)
.
Typical use case is:
public void reentrantMethod(Object param) { if (condition || tooManyReenters) fork(param) else call(param) }Calculating
tooManyReenters
usually involves using a ThreadLocal
and algebra on the
number of reentrant invocations, which is factored out in this class for convenience.
The same code using this class becomes:
private final ForkInvoker invoker = ...; public void reentrantMethod(Object param) { invoker.invoke(param); }
Constructor and Description |
---|
ForkInvoker(int maxInvocations)
Creates an instance with the given max number of reentrant calls to
#invoke(T)
If maxInvocations is zero or negative, it is interpreted
as if the max number of reentrant calls is infinite. |
Modifier and Type | Method and Description |
---|---|
abstract void |
call(T context)
Executes the direct, non-forked, invocation
|
protected boolean |
condition()
Subclasses should override this method returning true if they want
#invoke(T) to call #fork(T) . |
abstract void |
fork(T context)
Executes the forked invocation
|
boolean |
invoke(T context)
Invokes either
#fork(T) or #call(T) . |
public ForkInvoker(int maxInvocations)
#invoke(T)
If maxInvocations
is zero or negative, it is interpreted
as if the max number of reentrant calls is infinite.maxInvocations
- the max number of reentrant calls to #invoke(T)
public boolean invoke(T context)
#fork(T)
or #call(T)
.
If condition()
returns true, #fork(T)
is invoked.
Otherwise, if the max number of reentrant calls is positive and the
actual number of reentrant invocations exceeds it, #fork(T)
is invoked.
Otherwise, #call(T)
is invoked.context
- the invocation context#fork(T)
has been called, false otherwiseprotected boolean condition()
#invoke(T)
to call #fork(T)
.#invoke(T)
should call #fork(T)
, false otherwisepublic abstract void fork(T context)
context
- the invocation contextpublic abstract void call(T context)
context
- the invocation contextCopyright © 1995-2012 Mort Bay Consulting. All Rights Reserved.