qwerty
qwerty

Reputation: 393

Java: NullPointerException when trying to add object to BlockingQueue?

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?

Upvotes: 2

Views: 2983

Answers (4)

Ian Macalinao
Ian Macalinao

Reputation: 1668

  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.

Upvotes: 0

Scorpion
Scorpion

Reputation: 3976

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.

Upvotes: 1

NPE
NPE

Reputation: 500357

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".

Upvotes: 3

Micah Hainline
Micah Hainline

Reputation: 14427

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

Upvotes: 1

Related Questions