Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
The class is suitable for creating annotated commands that can execute on another thread. Target: trunk Require-notes: no Require-book: no Acked-by: Paul Millar <paul.millar@desy.de> Patch: http://rb.dcache.org/r/5598/
- Loading branch information
Showing
1 changed file
with
72 additions
and
0 deletions.
There are no files selected for viewing
72 changes: 72 additions & 0 deletions
72
modules/cells/src/main/java/dmg/util/command/DelayedCommand.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
package dmg.util.command; | ||
|
||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
import java.io.Serializable; | ||
import java.util.concurrent.Callable; | ||
import java.util.concurrent.Executor; | ||
|
||
import dmg.cells.nucleus.DelayedReply; | ||
import dmg.cells.nucleus.NoRouteToCellException; | ||
import dmg.cells.nucleus.Reply; | ||
|
||
/** | ||
* Abstract base class for annotated commands for executing the command | ||
* asynchronously using an executor. | ||
* | ||
* By default a new thread is spawned for each command. | ||
*/ | ||
public abstract class DelayedCommand<T extends Serializable> | ||
extends DelayedReply | ||
implements Callable<Reply>, Runnable | ||
{ | ||
private static final Logger LOGGER = LoggerFactory.getLogger(DelayedCommand.class); | ||
private static final Executor NEW_THREAD_EXECUTOR = new Executor() | ||
{ | ||
@Override | ||
public void execute(Runnable command) | ||
{ | ||
new Thread(command).start(); | ||
} | ||
}; | ||
|
||
private final Executor executor; | ||
|
||
protected DelayedCommand() | ||
{ | ||
this(NEW_THREAD_EXECUTOR); | ||
} | ||
|
||
protected DelayedCommand(Executor executor) | ||
{ | ||
this.executor = executor; | ||
} | ||
|
||
@Override | ||
public Reply call() throws Exception | ||
{ | ||
executor.execute(this); | ||
return this; | ||
} | ||
|
||
protected abstract T execute() throws Exception; | ||
|
||
@Override | ||
public void run() | ||
{ | ||
Serializable result; | ||
try { | ||
result = execute(); | ||
} catch (Exception e) { | ||
result = e; | ||
} | ||
try { | ||
send(result); | ||
} catch (NoRouteToCellException e) { | ||
LOGGER.warn("Failed to send reply: {}", e.getMessage()); | ||
} catch (InterruptedException e) { | ||
LOGGER.warn("Failed to send reply as request was interrupted"); | ||
} | ||
} | ||
} |