質問

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);
    }
}
役に立ちましたか?

解決

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)

他のヒント

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)){
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top