2

I want to instantiate a new java ThreadPoolExecutor with this piece of code:

public class ImageList {
    private LinkedBlockingQueue<Image> list;
    private final ThreadPoolExecutor executor;

    public ImageList() {
        executor = new ThreadPoolExecutor(2, 4, 100, TimeUnit.SECONDS, list);
    }
}

Where Image has the following header:

public class Image implements Runnable, Serializable

However, Java complains that a constructor for the type BlockingQueue<Runnable> was not found. What am I doing wrong?

2

1 Answer 1

4

The constructor expects a BlockingQueue<Runnable>. You pass it a BlockingQueue<Image>.

A BlockingQueue<Image> is not a BlockingQueue<Runnable>. Indeed, you may store any kind of Runnable in a BlockingQueue<Runnable>, but you may only store Image instances in a BlockingQueue<Image>.

If it were, you could do the following:

BlockingQueue<Image> list = new BlockingQueue<Image>();
BlockingQueue<Runnable> list2 = list1;
list2.add(new Runnable() {...});

and boom! your BlockingQueue<Image> would contain something other than an Image.

6
  • Wouldn't you be able to do BlockingQueue<? extends Runnable>?
    – jn1kk
    Jul 13, 2012 at 15:42
  • 1
    No. The thread pool needs a BlockingQueue<Runnable>, to be able to store the Runnable instances it creates in the queue. BlockingQueue<? extends Runnable> means: BlockingQueue of some unknown subclass which is or extends Runnable. You can't store anything into such a queue.
    – JB Nizet
    Jul 13, 2012 at 16:58
  • Doesn't Image implement ("extends") Runnable though? So you could put Images into BlockingQueue<? extends Runnable>, or am I wrong (or misunderstanding OP's question)?
    – jn1kk
    Jul 13, 2012 at 17:25
  • You're wrong. Read my answer: it should answer your question: BlockingQueue<? extends Runnable> list = new BlockingQueue<Image>();BlockingQueue<Runnable> list2 = list1;list2.add(new Runnable() {...});// boom!
    – JB Nizet
    Jul 13, 2012 at 17:35
  • You are right. That would only work if you could change the constructor. Constructor expects a queue of Runnable. But queue of Runnable is not a queue of Image. Thanks.
    – jn1kk
    Jul 13, 2012 at 17:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.