/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.cassandra.db;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.net.IVerbHandler;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;

public class ReadVerbHandler implements IVerbHandler
{
    protected static class ReadContext
    {
        protected ByteArrayInputStream bufIn_;
        protected DataOutputBuffer bufOut_ = new DataOutputBuffer();
    }

    private static Logger logger_ = LoggerFactory.getLogger( ReadVerbHandler.class );
    /* We use this so that we can reuse readcontext objects */
    private static ThreadLocal<ReadVerbHandler.ReadContext> tls_ = new InheritableThreadLocal<ReadVerbHandler.ReadContext>();

    public void doVerb(Message message, String id)
    {
        byte[] body = message.getMessageBody();
        /* Obtain a Read Context from TLS */
        ReadContext readCtx = tls_.get();
        if ( readCtx == null )
        {
            readCtx = new ReadContext();
            tls_.set(readCtx);
        }
        readCtx.bufIn_ = new ByteArrayInputStream(body);

        try
        {
            if (StorageService.instance.isBootstrapMode())
            {
                /* Don't service reads! */
                throw new RuntimeException("Cannot service reads while bootstrapping!");
            }
            ReadCommand command = ReadCommand.serializer().deserialize(new DataInputStream(readCtx.bufIn_), message.getVersion());
            Table table = Table.open(command.table);
            Row row = command.getRow(table);
            ReadResponse readResponse = getResponse(command, row);
            /* serialize the ReadResponseMessage. */
            readCtx.bufOut_.reset();

            ReadResponse.serializer().serialize(readResponse, readCtx.bufOut_, message.getVersion());

            byte[] bytes = new byte[readCtx.bufOut_.getLength()];
            System.arraycopy(readCtx.bufOut_.getData(), 0, bytes, 0, bytes.length);

            Message response = message.getReply(FBUtilities.getBroadcastAddress(), bytes, message.getVersion());
            if (logger_.isDebugEnabled())
              logger_.debug(String.format("Read key %s; sending response to %s@%s",
                                          ByteBufferUtil.bytesToHex(command.key), id, message.getFrom()));
            MessagingService.instance().sendReply(response, id, message.getFrom());
        }
        catch (IOException ex)
        {
            throw new RuntimeException(ex);
        }
    }

    public static ReadResponse getResponse(ReadCommand command, Row row)
    {
        if (command.isDigestQuery())
        {
            if (logger_.isDebugEnabled())
                logger_.debug("digest is " + ByteBufferUtil.bytesToHex(ColumnFamily.digest(row.cf)));
            return new ReadResponse(ColumnFamily.digest(row.cf));
        }
        else
        {
            return new ReadResponse(row);
        }
    }
}

@@ -1391,176 +1391,8 @@
 r%0A%7B%0A
-    protected static class ReadContext%0A    %7B%0A        protected ByteArrayInputStream bufIn_;%0A        protected DataOutputBuffer bufOut_ = new DataOutputBuffer();%0A    %7D%0A%0A
     
@@ -1477,597 +1477,359 @@
  );%0A
+%0A
     /
-* We use this so that we can reuse readcontext objects */%0A    private static ThreadLocal%3CReadVerbHandler.ReadContext%3E tls_ = new InheritableThreadLocal%3CReadVerbHandler.ReadContext%3E();%0A%0A    public void doVerb(Message message, String id)%0A    %7B%0A        byte%5B%5D body = message.getMessageBody();%0A        /* Obtain a Read Context from TLS */%0A        ReadContext readCtx = tls_.get();%0A        if ( readCtx == null )%0A        %7B%0A            readCtx = new ReadContext();%0A            tls_.set(readCtx);%0A        %7D%0A        readCtx.bufIn_ = new ByteArrayInputStream(body);%0A%0A        try%0A    
+/ re-use output buffers between requests%0A    private static ThreadLocal%3CDataOutputBuffer%3E threadLocalOut = new ThreadLocal%3CDataOutputBuffer%3E()%0A    %7B%0A        @Override%0A        protected DataOutputBuffer initialValue()%0A        %7B%0A            return new DataOutputBuffer();%0A        %7D%0A    %7D;%0A%0A    public void doVerb(Message message, String id)%0A
     %7B%0A
-    
     
@@ -1891,61 +1891,10 @@
     
-    %7B%0A                /* Don't service reads! */%0A    
+%7B%0A
     
@@ -1978,29 +1978,138 @@
 %22);%0A        
+%7D%0A%0A
     
-%7D
+    try%0A        %7B%0A            ByteArrayInputStream in = new ByteArrayInputStream(message.getMessageBody());
 %0A           
@@ -2192,22 +2192,10 @@
 eam(
-readCtx.bufIn_
+in
 ), m
@@ -2306,32 +2306,33 @@
 .getRow(table);%0A
+%0A
             Read
@@ -2331,154 +2331,53 @@
     
-ReadResponse readResponse = getResponse(command, row);%0A            /* serialize the ReadResponseMessage. */%0A            readCtx.bufOut_.res
+DataOutputBuffer out = threadLocalOut.g
 et();%0A
-%0A
     
@@ -2424,20 +2424,19 @@
 ize(
-read
+get
 Response
 , re
@@ -2435,25 +2435,27 @@
 onse
-, readCtx.bufO
+(command, row), o
 ut
-_
 , me
@@ -2475,17 +2475,16 @@
 ion());%0A
-%0A
         
@@ -2511,31 +2511,19 @@
 ew byte%5B
-readCtx.bufO
+o
 ut
-_
 .getLeng
@@ -2562,23 +2562,11 @@
 opy(
-readCtx.bufO
+o
 ut
-_
 .get
@@ -2601,17 +2601,16 @@
 ength);%0A
-%0A
         
@@ -2706,32 +2706,33 @@
 .getVersion());%0A
+%0A
             if (

clean up ReadVerbHandler