开发者

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.


  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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜