Search code examples
javarunnableserializablethreadpoolexecutor

Java ThreadPoolExecutor with Serializable and Runnable queue elements (Compile error: no suitable constructor found for...)


I am trying to create a replicated BlockingQueue implementation to use in a cluster environment as a distributed task cache.

Since it has to be distributed i need all elements of the queue to be Serializable. This is how i define the class;

public class ReplicatedBlockingQueue<E extends Serializable> implements BlockingQueue<E>

Then i create a blocking queue implementation with Runnable "Job" class, which is both Serializable and Runnable

public class Job implements Runnable,Serializable

By the time i use this queue to create a ThreadPoolExecutor, Java complains that ReplicatedBlockingQueue is not a defined constructor

new ThreadPoolExecutor(4,4, new ReplicatedBlockingQueue<Job>());

If Runnable interface was extending Serializable i would be able to create replicated queue as follows:

new ThreadPoolExecutor(4,4, new ReplicatedBlockingQueue<Runnable>());

But unfortunately Runnable is not Serializable

How can i use my ReplicatedBlockingQueue implementation with ThreadPoolExecutor ?

EDIT: Using Java6

EDIT: Posted the example on the following link. You can compile online by clicking edit button. http://ideone.com/JFFDNa


Solution

  • There is no simple way to tell the compiler you know the type will be fine. In this situation it is easier to use an unchecked type.

    // produces a warning but works.
    new ThreadPoolExecutor(4,4, new ReplicatedBlockingQueue());
    

    You can add @SuppressWarnings("unchecked") to the method to turn the warning off.