2

I found a similar question about a PriorityQueue, the error with that one was that it wasn't initialized correctly. I might have the same problem, but i can't figure out how to initialize it correctly!

As of now i just do:

BlockingQueue myQueue = null;

but that throws an exception as soon as i try to add something to the list.

How do i correctly initialize a BlockingQueue?

4 Answers 4

3

BlockingQueue<E> is an interface. You need to pick a specific implementation of that interface, such as ArrayBlockingQueue<E>, and invoke one of its constructors like so:

BlockingQueue<E> myQueue = new ArrayBlockingQueue<E>(20);

If you're unsure what different types of blocking queues exist in the JDK, look under "All Known Implementing Classes".

Sign up to request clarification or add additional context in comments.

Comments

1

If you call any method on null you will get a null pointer exception. Try making a new ArrayBlockingQueue, which implements the interface.

Comments

1

Please read the javadocs which also has examples http://download.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html

BlockingQueue blockingQueue = new ArrayBlockingQueue(100); // there are other implementations as well, in particular that uses a linked list and scales better than the array one.

Comments

0
  1. Make BlockingQueue hold a certain type, for example BlockingQueue<String> or something similar.
  2. You need to initialize the variable with an implementation of BlockingQueue, for example ArrayBlockingQueue<E>.

So do something like:

BlockingQueue<MyObject> = new ArrayBlockingQueue<MyObject>();

and you'll be fine.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.