aufziehvogel
aufziehvogel

Reputation: 7297

Generics in construct: Java does not recognize that my own class implements an interface

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?

Upvotes: 2

Views: 313

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

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.

Upvotes: 4

Related Questions