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?
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".
If you call any method on null you will get a null pointer exception. Try making a new ArrayBlockingQueue, which implements the interface.
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.
- Make
BlockingQueue
hold a certain type, for exampleBlockingQueue<String>
or something similar. - You need to initialize the variable with an implementation of
BlockingQueue
, for exampleArrayBlockingQueue<E>
.
So do something like:
BlockingQueue<MyObject> = new ArrayBlockingQueue<MyObject>();
and you'll be fine.
精彩评论