title: Java NIO ByteBuffer.put null pointer exception
body: <p>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 </p>
  
  <blockquote>
    <p>localBuffer.put(sendLengthBuffer,0,sendLengthBuffer.length);</p>
  </blockquote>
  
  <p>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.</p>
  
  <p>Code:</p>
  
  <pre><code>public void write(SocketChannel sc,PayloadLength pl,ArrayBlockingQueue&lt;byte[]&gt; queue) throws IOException{
          while(!queue.isEmpty()){
              byte[] message = queue.poll();
              if(message != null &amp;&amp; message.length &gt; 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;
                  }
  
              }
          }
  </code></pre>
  
  <p>And here is the stack trace:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>****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!</p>