Why java.util.ScheduledThreadPoolExecutor violates the Open-Close-Principle

In my last post I described the concept of the NotifyingExecutorService. In short, it is a ThreadPoolExecutor (TPE)-extension that returns Future-objects one can listen to. I thought it was a good idea to adopt that pattern to java’s ScheduledThreadPoolExecutor (STPE) which allows the execution of delayed and periodic tasks. However, I failed hard.

The STPE extends the normal ThreadPoolExecutor and adds several schedule()-methods to execute tasks in the future and/or allow repetition of tasks with a fixed frequence. Whenever a schedule-method gets called it creates a new ScheduledFutureTask – object that holds the incoming task and some timing parameters. The method then calls decorateTask() and adds the resulting ScheduledFutureTask to the work queue:

public  ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) {
        if (callable == null || unit == null)
            throw new NullPointerException();
        if (delay < 0) delay = 0;
        long triggerTime = now() + unit.toNanos(delay);
        RunnableScheduledFuture t = decorateTask(callable,
            new ScheduledFutureTask(callable, triggerTime));
        delayedExecute(t);
        return t;
    }

protected  RunnableScheduledFuture decorateTask(
        Callable callable, RunnableScheduledFuture task) {
        return task;
    }

As you can see, decorateTask() returns the incoming task by default. Javadoc and I thought this was a good place to install the NotifyingFuture-concept:

  • Decorate the incoming task.
  • Add register-methods.
  • Notify listener when certain methods are called.

So I created a class that decorates the original task and overwrites the run()-method in the following manner:

@Override
    public void run() {
    	/*
    	 * execute task
    	 */
        this.decorate.run();
        /*
         * notify listener
         */
        notifyListener();
    }

Sadly, this approach works only for one-shot-executions. Periodic tasks won’t notify their listener and the reason lies in the nature of the decorator pattern that is used by the STPE. See the following snippet of the delegated ScheduledFutureTask (which is a private class inside the ScheduledThreadPoolExecutor):

/**
         * Runs a periodic task.
         */
        private void runPeriodic() {
            boolean ok = ScheduledFutureTask.super.runAndReset();
            boolean down = isShutdown();
            // Reschedule if not cancelled and not shutdown or policy allows
            if (ok && (!down ||
                       (getContinueExistingPeriodicTasksAfterShutdownPolicy() &&
                        !isStopped()))) {
                long p = period;
                if (p > 0)
                    time += p;
                else
                    time = now() - p;
                ScheduledThreadPoolExecutor.super.getQueue().add(this);
            }
            // This might have been the final executed delayed
            // task.  Wake up threads to check.
            else if (down)
                interruptIdleWorkers();
        }

        /**
         * Overrides FutureTask version so as to reset/requeue if periodic.
         */
        public void run() {
            if (isPeriodic())
                runPeriodic();
            else
                ScheduledFutureTask.super.run();
        }

When the task is periodic, runPeriodic() is called which is the root of all evil. Can you spot the pitfall? If not, look closer to line 16.
When the STPE is not yet shut down, the task adds itself to the queue. Remeber that we decorated that task, we didn’t subclass it. That means although the initial task contained our NotifyingFutureTask-implementation, whenever a task is periodic it get’s rid of it’s enclosing deocrator on the second execution.

Now tell me: how bad is that? Why has Sun chosen to use two different approaches (newTaskFor vs decorateTask) inside one class? Who knows the answer?

Advertisements

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.

Simple XML-deserialization using SimpleXML

Whenever you need to read-in some parameters to your java-application you have to chose the right format. In order to make the right descision, it is necessary to know what kind of data to store. Things are clear when you have key-value-data like this:
parameter1 = 1
parameter2 = 10
parameter3 = 25

To store such key-value-data you should use java.util.Properties. You can easily load such a file in three lines of code:

//Load
File f = new File(fileName);
Properties properties = new Properties();
properties.load(new FileReader(f));
//Retrieve data
String parameterName = "parameter1";
String property1 = properties.getProperty(parameterName);

However a key-value-store is not appropriate when the data to store

  • has it’s own format or
  • when a key can have more than one property or
  • when you want to map objects to your properties.

If one point is true for your data then you should have a look at XML-format. However, some years ago, it was pain to handle XML in Java (and I don’t speak of object-mapping here…). Gladly, things have changed and there exists the wonderful SimpleXML Framework in the Java-universe that helps you with both XML-serialization (write POJOs to XML) and XML-deserialization (read XML and map them to POJOs).

Read a XML-file

This example refers to the Strategy-Pattern-post I made earlier.

Imagine you want to read-in some calculations via XML. When you have a look at the Strategy-Pattern-Example you will find out, that a calculation consists of:

  • an operator
  • and two variables

Let’s define the class Calculation which stores those properties.

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Root;

@Root(name="calculation")
public class Calculation {

	@Attribute
	private Operator operator;

	@Attribute
	private int valueA;

	@Attribute
	private int valueB;

}

The @Root-annotation says that this class needs can be serialized and mapped to an XML-element. The name-parameter defines the name of this element inside the XML-file. When no name is given, it defaults to the name of the class or field. The @Attribute-annotation specifies fields that are attribues (of an element) in terms of XML-specification.
Because one should have the possibility to calculate more than one calculation, we define the Calculations-class:

import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root(name="config")
public class Calculations {

	@ElementList(name="calculations")
	private List calculations;

}

This mapping-class is also pretty much straightforward. The @ElementList-annotation allows you to load multiple data-sets from the XML-file. You can also use @ElementArray for arrays of data or @ElementMap for java.util.Map-equivalent. (Note that you have to define the length of the array in your XML-file (length=”123″) as an attribute of the element that holds the annotation when using @ElementArray.)

Now let’s take a look to the XML-file with some example-data:

<config>
	<calculations>
		<calculation operator="ADD" valueA="1" valueB="2"/>
	</calculations>
</config>

We found out that mapping the XML to a POJO was easy. What about loading that file? As you will see, loading files with SimpleXML is also no rocket-science:

Serializer serializer = new Persister();
File file = new File("calculations.xml");
Calculations calculations = serializer.read(Calculations.class, file);

That’s all! No complex file-handling, no new lines of code (except of adding some annotations).
Watch out for my next posts that will show you how to:

Simple XML-serialization using Simple XML

In my last post I introduced Simple XML as an easy to use XML-Object mapper. I showed how to map XML-files to POJOs.
In this post I’ll deal with the other way round: store POJOs to XML-files. To show you how this is done with Simple XML, I’ll utilize and extend the calculator-example again.
After we have loaded the calculations, we should calculate them and store the results to our new Result-classes:

@Root(name=&quot;result&quot;)
public class Result {

	@Attribute
	private final int result;

	public Result(int result) {
		super();
		this.result = result;
	}

}
@Root(name=&quot;config&quot;)
public class Results {

	@ElementList
	private List results;

	public Results(List results) {
		this.results = results;
	}

}

There are no new annotations, just POJOs. In order to store the results, I modified the existing Calculation(s)-classes:

@Root(name=&quot;calculation&quot;)
public class Calculation {

	@Attribute
	private Operator operator;

	@Attribute
	private int valueA;

	@Attribute
	private int valueB;

	public Result getResult(){
		return new Result(operator.calculate(valueA, valueB));
	}
}
@Root(name=&quot;config&quot;)
public class Calculations {

	@ElementList(name=&quot;calculations&quot;)
	private List calculations;

	public List calculateAll(){
		List results = new ArrayList();
		for(Calculation c:calculations){
			results.add(c.getResult());
		}
		return results;
	}

}

What steps do we have to perform now?

  • Read the calculations from calculations.xml
  • Calculate the results
  • Store the results into results.xml

Translated into code, this is what it looks like:

        public static void main(String[] args) throws Exception {
		write(calculate(read()));
	}

	public static Calculations read() throws Exception{
		Serializer serializer = new Persister();
		File file = new File(&quot;calculations.xml&quot;);
		return serializer.read(Calculations.class, file);
	}

	public static Results calculate(Calculations calculations){
		return new Results(calculations.calculateAll());
	}

	public static void write(Results results) throws Exception{
		Serializer serializer = new Persister();
		File file = new File(&quot;results.xml&quot;);
		serializer.write(results, file);
	}

As you can see, serializing to XML is also pretty easy and nothing compared to the common DOM or SAX-frameworks.
Finally, let’s take a look at the written xml-file:

&lt;config&gt;
  &lt;results class=&quot;java.util.ArrayList&quot;&gt;
    &lt;result result=&quot;3&quot;/&gt;
  &lt;/results&gt;
&lt;/config&gt;

This is almost what we expected, except of the new class-attribute in results-element. This attribute is automatically generated by Simple XML to determine the implementation of the java.util.List-interface that was used while the file was serialized (we created a new ArrayList instance in line 8 of Calculations-class). Whenever the file gets deserialized an instance of this class will be used to store the results (defaults to java.util.ArrayList).

JPA EntityManager.unwrap()-method

Last week I came in touch with the very useful

EntityManager.<T>unwrap(Class<T>)

-method from the javax.persistence-package. The method can be used to gain access of JPA-vendor-specific classes. At work, we are running Hibernate in “JPA-mode” which means we do only have access to methods that are provided by the EntityManager-interface. It was ok to us, until we wanted to get rid of those SELECT-statements that the EntityManager.merge()-method does before the UPDATE-statement is fired to the database. If we were running Hibernate in “Hibernate-mode” we wouldn’t have any problems at all: the EntityManager-equivalent Session-class offers a update()-method which fires only the UPDATE-Statement without any SELECTs. This is where the unwrap-method comes into play. Just fetch an EntityManager-instance via injection or create a new one on your own via EntityManagerFactory and place the following snippet into your code:

EntityManager em = ...
Session session = em.unwrap(Session.class);
//em.merge(myEntity);
session.update(myEntity);

Thanks to axtavt for his/her advice.

Combining Delegation- and Strategy-Pattern using an Enum

The Delegation- and  Strategy-patterns are extremly useful when you need to implement some operations (strategies) and want to bundle them in one class. I won’t explain the patterns in detail here, but give you an example of how to combine both of them.

Imagine the following interface which represents the “strategy” to implement:

public interface Calculatable {

/**
* Calculate something.
* @param valueA
* @param valueB
* @return
*/
public int calculate(int valueA, int valueB);

}

Now we have some concrete “strategy-implementations” which represent the four basic arithmetic operations:

class Add implements Calculatable{
@Override
public int calculate(int valueA, int valueB) {
return valueA + valueB;
}
}
class Subtract implements Calculatable{
@Override
public int calculate(int valueA, int valueB) {
return valueA - valueB;
}
}
class Multiply implements Calculatable{
@Override
public int calculate(int valueA, int valueB) {
return valueA * valueB;
}
}
class Divide implements Calculatable{
@Override
public int calculate(int valueA, int valueB) {
return valueA / valueB;
}
}

Nothing special until here, just a straight-forward implementation of the strategy-pattern.
But now we introduce the Delegation-pattern using an Enum.

public enum Operator implements Calculatable{
ADD(new Add()),
SUBTRACT(new Subtract()),
MULTIPLY(new Multiply()),
DIVIDE(new Divide())
;

private final Calculatable delegate;

private Operator(Calculatable delegate) {
this.delegate = delegate;
}

@Override
public int calculate(int valueA, int valueB) {
return this.delegate.calculate(valueA, valueB);
}

}

This enum does not implement the strategy provided by Calculateble-interface but just delegates it to the other implementations. What are the benefits:

  • All operations in one class
  • Having the four implementations placed inside the enum as nested classes ensures singleton-behaviour
  • Smart access to the strategies via enum
public static void main(String[] args) {
System.err.println(Operator.ADD.calculate(5, 5));
System.err.println(Operator.SUBTRACT.calculate(5, 5));
System.err.println(Operator.MULTIPLY.calculate(5, 5));
System.err.println(Operator.DIVIDE.calculate(5, 5));
}

Happy coding!

http://en.wikipedia.org/wiki/Strategy_pattern

http://en.wikipedia.org/wiki/Delegation_pattern