its my first post so go easy on me :). I'm working on refactoring some connectivity code to use non-blocking IO and am running into a null point exception when calling byteButter.put(byte[]) or byteBuffer.put(byte[],index,length). The exception is occurring on this line
localBuffer.put(sendLengthBuffer,0,sendLengthBuffer.length);
The strange thing is the null pointer only occurs on the first time I call the method, all subsequent attempts to write are functioning as intended.
Code:
public void write(SocketChannel sc,PayloadLength pl,ArrayBlockingQueue<byte[]> queue) throws IOException{
while(!queue.isEmpty()){
byte[] message = queue.poll();
if(message != null && message.length > 0){
if(bufferHasRemaining()){
SystemLogger.getLogger().logMe(LoggerLevel.INFO, this.getClass().getSimpleName(), "writer compacting");
localBuffer.compact();
}else{
SystemLogger.getLogger().logMe(LoggerLevel.INFO, this.getClass().getSimpleName(), "writer compacting");
localBuffer.clear();
}
//calculate the message length
byte[] sendLengthBuffer = new byte[pl.getLengthSize()];
pl.parseWriteLength(sendLengthBuffer, message.length);
localBuffer.put(sendLengthBuffer,0,sendLengthBuffer.length);
localBuffer.put(message,0,message.length);
localBuffer.flip();
// //write until buffer is empty
// //TODO: potential infinite loop here
// while(localBuffer.hasRemaining()){
// sc.write(localBuffer);
// }
sc.write(localBuffer);
if(bufferHasRemaining()){
//could not write all bytes to channel, most likely the sockets write buffer is full
break;
}
}
}
And here is the stack trace:
EXCEPTION: null - null
STACK TRACE:
java.nio.HeapByteBuffer.put(HeapByteBuffer.java:189)
com.discover.paymentservices.commons.net.nio.NIOWriteHandler.write(NIOWriteHandler.java:57)
com.discover.paymentservices.tibco.channel.nio.BaseNIOConnectionHandler.run(BaseNIOConnectionHandler.java:603)
****EDIT***** Turns out the null pointer was a result of calling byteBuffer.compact() immediately after allocating the byteBuffer. Still not certain why the null pointer gets thrown on the put() in this scenario but I seem to have found a solution. Thanks for the comments!