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

StackOverflow https://stackoverflow.com/questions/20766324

سؤال

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

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

ThreadPoolExecutor expects a BlockingQueue<Runnable>, which ReplicatedBlockingQueue isn't, since it is a BlockingQueue<E extends Serializable>.

You need to declare ReplicatedBlockingQueue<E extends Serializable & Runnable> to make E extend Runnable and be usable as a return type for the methods inherited from BlockingQueue, and you must parametrize BlockingQueue with Runnable, as it is the explicitly expected type for ThreadPoolExecutor.

public class ReplicatedBlockingQueue<E extends Serializable & Runnable> 
            implements BlockingQueue<Runnable> {
    @Override
        public E remove() {
        }

...

ThreadPoolExecutor requires a non generic BlockingQueue so try this:

new ThreadPoolExecutor( 4, 4, keepAlive, timeUnit, new ReplicatedBlockingQueue<Runnable>() );
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top