Notifying ExecutorService (2)

This is the second post about the NotifyingExecutorService. Don’t miss the first half!

The ThreadPoolExecutor in the java.util.concurrency package has several methods for submitting tasks. Each method wraps the incoming Runnable (or Callable) to a FutureTask containing that task and the future result by forwarding the submit()-methods  to the protected method newTaskFor(). The FutureTask itself has also some interesting methods to observe the state of the task (isDone(), iscancelled() for instance). Additionally the done()-method gets called when the task has been processed by the TPE – despite of whether the computation of the task failed or completed. By default, this method does nothing and is therefore intended to be overridden. This is a good entrypoint for the listener-modell described above:

1.    Create a subclass of FutureTask, override done() and add a method to register a listener to the task. Notify listener (if registered) when done() gets called.
2.    Create a subclass of ThreadPoolExecutor and return the subclassed FutureTask whenever newTaskFor() gets called.
3.    Return the subclassed FutureTask on every submit()-method instead of a plain Future to allow registration of listeners to a task.

That’s almost all. Everything is cool, isn’t it? Unfortunately no, because of two major problems that one has to be aware of:
1.    We have to ensure that the  listener gets notified although the task has been already executed. Remember that submitting tasks to the TPE is an asynchronous operation. The caller-thread adds the FutureTask to a queue and returns immediately. Meanwhile pool-threads are working on the queue. There is no guarantee what happens first: adding a listener to the task (by caller thread) or computing the result of the task (by pool-thread). Which leads us directly to the second problem:
2.    The thread that notifies the listeners is not the caller-thread it’s one of the pool-threads. That means that every computation that is made by the listener is done by a pool-thread. This is very bad, because a TPE is normally added to achieve decoupling. We would break the design when long running tasks are implied by the listener’s callback-method. Remember the game-example from above:

•    New Gameobject is created by gamelogic. (Thread A)
•    A “persist task” is added to our database-TPE which persists the object into the database (and assigns a new id to the object).  (Pool Thread B)
•    We register a callback-listener to the FutureTask returned by TPE. When notified, the listener sends the new Gameobject to the connected clients. (Thread A)
•    Database-TPE executes task and notifies listener. The messages are send to clients. (Pool Thread B)

The last operation should not be done by a pool-thread, because the pool should only execute database-tasks. The solution of the problem is to define a TPE that executes the callback-tasks when the FutureTask is done, simply by adding a TPE-parameter to the addListener()-method. Sadly this solution has a tiny disadvantage: passing a task to a TPE comes with some performance tradeoffs. When the listener-callbacks aren’t expensive you might consider executing the callback in the pool-thread. Google’s guava-library helps us in this case: use their MoreExecutors.sameThreadExecutor() which executes all submitted tasks in the caller thread.

Finallay, here are the classes:

public interface INotifyingExecutorService extends ExecutorService{

    @Override
    public <T> INotifyingFuture<T> submit(Callable<T> task);
    
    @Override
    public INotifyingFuture<Void> submit(Runnable task);
    
    @Override
    public <T> INotifyingFuture<T> submit(Runnable task, T result);
    
}

As you can see, this interface just extends the ExecutorService to enforce that an INotifyingFuture has to be returned by any INotifyingExecutorService.

public class NotifyingExecutorService extends ForwardingExecutorService implements INotifyingExecutorService{

    private final ExecutorService delegate;
    
    public NotifyingExecutorService(ExecutorService delegate) {
		super();
		this.delegate = delegate;
	}

	@Override
    public <T> INotifyingFuture<T> submit(Callable<T> task) {
    	if (task == null) throw new NullPointerException();
    	INotifyingFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }
    
	@Override
    public INotifyingFuture<Void> submit(Runnable task) {
    	if (task == null) throw new NullPointerException();
        INotifyingFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }
    
	@Override
    public <T> INotifyingFuture<T> submit(Runnable task, T result) {
    	if (task == null) throw new NullPointerException();
    	INotifyingFuture<T> ftask = newTaskFor(task, result);
        execute(ftask);
        return ftask;
    }

    
	@Override
	protected ExecutorService delegate() {
		return this.delegate;
	}
    
	protected <T> INotifyingFuture<T> newTaskFor(Callable<T> callable) {
		return new NotifyingFuture<T>(callable);
	}
	
	protected <T extends Object> INotifyingFuture<T> newTaskFor(Runnable runnable, T value) {
		return new NotifyingFuture<T>(runnable, value);
	}
}

This class implements the new INotifyingExecutorService and extends guavas ForwardingExecutorService. This special ExecutorService implementation delegates all calls to any ExecutorService-instance that is passed into the constructor.

public interface INotifyingFuture<V> extends RunnableFuture<V>{

    /**
     * Sets this listener to a {@link INotifyingFuture}. When the future is done
     * or canceled the listener gets notified.<br> 
     * @param listener
     * @param the executor that executes the shiet.
     */
    public void setListener(IFutureListener<V> listener, ExecutorService executor);
    
    /**
     * Sets this listener to a {@link INotifyingFuture}. When the future is done
     * or canceled the listener gets notified.<br>
     * <b>Attention</b>: Be aware of the fact that everything that is done in that
     * listener is executed in same thread as the original task that this listener listens
     * to. Only use this method when you are sure that no long running task is performed
     * by the listener. When you want the listener's tasks to be performed asynchronous
     * use {@link #setListener(IFutureListener, ExecutorService)} instead.
     * @param listener
     */
    public void setListener(IFutureListener<V> listener);
}
public interface IFutureListener<V> {
	
	/**
	 * The task was computed successfully.
	 * @param result
	 */
	public void onSuccess(V result);
	
	/**
	 * called when future state is canceled.
	 */
	public void onCancel(RunnableFuture<V> cancelledFuture);
	
	/**
	 * Called when there was an error while executing 
	 * this future.
	 * @param e
	 * @param future the future that fails
	 */
	public void onError(Throwable e, Future<V> future);
}
public class NotifyingFuture<V> extends FutureTask<V> implements INotifyingFuture<V>{

    private static final ExecutorService DEFAULT_EXECUTOR = MoreExecutors.sameThreadExecutor();
    
	private IFutureListener<V> listener = null;
	private ExecutorService executor = null;
	private final AtomicBoolean executed = new AtomicBoolean();
	
	public NotifyingFuture(Callable<V> callable) {
		super(callable);
		setExecutor(DEFAULT_EXECUTOR);
	}

	public NotifyingFuture(Runnable runnable, V result) {
        super(runnable,result);
        setExecutor(DEFAULT_EXECUTOR);
    }

	
	@Override
	protected void done() {
	    if(listener==null){
	        return;
	    }
	    notifyListenerOnce();
	}

	/**
	 * Atomically executes the task only one time.
	 */
	protected void notifyListenerOnce(){
		if(!this.executed.getAndSet(true)){
			notifyListener();
		}
	}
	
	protected void notifyListener(){
		this.executor.submit(new TaskCompletionRunner<V>(delegateFuture(),this.listener));
	}
	
	/**
	 * @return the future that was processed.
	 */
	protected RunnableFuture<V> delegateFuture(){
		return this;
	}
	
	@Override
	public void setListener(IFutureListener<V> listener, ExecutorService executor) {
		setExecutor(executor);
		setListener(listener);
	}
	
	public void setExecutor(ExecutorService executor) {
        this.executor = executor;
    }

    @Override
    public void setListener(IFutureListener<V> listener) {
        this.listener = listener;
        /*
         * Probably the task was already executed. If so, call done() manually. 
         */
        runWhenDone();
    }
    
    protected void runWhenDone(){
    	if(isDone()){
        	notifyListenerOnce();
        }
    }
    
    private static class TaskCompletionRunner<V> implements Runnable{

        private final IFutureListener<V> listener;
        private final RunnableFuture<V> future;
        
        public TaskCompletionRunner(RunnableFuture<V> future, IFutureListener<V> listener) {
            this.future = future;
            this.listener = listener;
        }
        
        @Override
        public void run() {
            if(this.future.isCancelled()){
                this.listener.onCancel(this.future);
            }else{
                try {
                    this.listener.onSuccess(this.future.get());
                } catch (InterruptedException e) {
                    this.listener.onError(e, this.future);
                } catch (ExecutionException e) {
                    this.listener.onError(e, this.future);
                }
            }
        }
        
    }
}

Happy coding!

Notifying ExecutorService (1)

The java.util.concurrent.ExecutorService and it’s implementations are great to take advantage of today’s multicore systems. You can submit a task from Thread A and it will be queued until a (worker) Thread B from the ExecutorService takes it and calculates the result (this is also an example of how the Producer-Consumer-Pattern can be implemented, but that is not the reason of this post ;-). When a task is submitted by a thread, the thread returns immediately holding a java.util.concurrent.Future returned by the ExecutorService’s submit-methods. There is no blocking operation until someone calls get() on the returned Future (and the calculation of the Future has not yet been completed) to obtain the result of the computation. If however Thread A has a lot of work to do and the computation of the task takes a lot of time, this can be a problem.

Imagine the following example: you’re developing a game with the following participants: a game-client to visualize the game and read the user’s input, a server that validates and processes the client-data and a database that persists all relevant gamedata. Whenever a new gameobject (whatever that might be) is created by the gamelogic this object must be persisted into the database. To decouple gamelogic from database-operations you choose to submit all db-relevant tasks to an ExecutorService. Additionaly the communication between client and server is based on the id of the gameobjects which is assigned by the database.

  1. Client reacts on user’s input: Create new uber-soldier!
  2. Client sends request to server.
  3. Server (Thread A) validates request and creates a new task that is submitted to database-layer (Thread B).
  4. Thread A calls Future.get() to obtain the new uber-soldier-id. Thread A waits until Thread B is done (database assigned primary key).
  5. Server sends response to client with new uber-soldier-id.

Problems may arise when Thread A must handle messages from hundreds or thousands of clients. The longer the key-assignment by the database takes, the longer Thread A must wait. Sooner or later this leads into slow pings for every client. Players leave, your company is about to get broke. What to do?

One option is to assign the primary-keys not by database but by the game-server itself. However this gets complicated when several servers writing on several databases. Another option is a variant of the Observer-pattern. What if you could register Thread A as a listener on the future? Instead of blocking through a call on Future.get(), the listener would be notified when the key-assignment by the database is done. Great! Let me introduce the concept of NotifyingExecutorService.

While thinking about the problem, I found myself crawling through the internet and some libraries to make sure I won’t reinvent the wheel. Finally I stumbled upon the (awesome) guava-library (version 10+), and found their solution of the problem called ListeningExecutorService. That was almost all I was looking for: register to a (extended) Future and get notified when computation is done. Sadly the google-implementation only notifies the listener without passing the result to them. I did not know why they made this, but that is where I started coding.

To the second part.