Skip to content

Commit

Permalink
Add DelayedCommand base class
Browse files Browse the repository at this point in the history
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
gbehrmann committed May 27, 2013
1 parent 7169e3e commit f2e9824
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions modules/cells/src/main/java/dmg/util/command/DelayedCommand.java
@@ -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");
}
}
}

0 comments on commit f2e9824

Please sign in to comment.