1

I wanna check a head element before taking but raises
java.lang.NullPointerException when peeking,

using java BlockingQueue

 BlockingQueue sharedQueue = new LinkedBlockingQueue() 

this is my code, any ideas?

while(true){ try { if(!sharedQueue.isEmpty()){ char ch = (char)sharedQueue.peek(); if(Character.isDigit(ch)){ digitTextField.setText(digitTextField.getText()+sharedQueue.take()); } } } catch (InterruptedException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } } 

2 Answers 2

4

It's because you're casting to char which doesn't allow nulls. Also, don't do sharedQueue.isEmpty() followed by peek - that is known as "check-then-act" which is a well-known cause of races.

You should define sharedQueue as BlockingQueue<Character> then use

if ((Character c = sharedQueue.poll()) != null)

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

Comments

1

peek() returns null when element not found:

Returns: the head of this queue, or null if this queue is empty

You need to use:

 if(ch != null && Character.isDigit(ch)){ 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.