/*
 * Licensed to ElasticSearch and Shay Banon under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. ElasticSearch 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.elasticsearch.common.io.stream;

import jsr166y.LinkedTransferQueue;
import org.elasticsearch.common.compress.Compressor;
import org.elasticsearch.common.io.UTF8StreamWriter;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 */
public class CachedStreamOutput {

    private static Entry newEntry() {
        BytesStreamOutput bytes = new BytesStreamOutput();
        HandlesStreamOutput handles = new HandlesStreamOutput(bytes);
        return new Entry(bytes, handles);
    }

    public static class Entry {
        private final BytesStreamOutput bytes;
        private final HandlesStreamOutput handles;

        Entry(BytesStreamOutput bytes, HandlesStreamOutput handles) {
            this.bytes = bytes;
            this.handles = handles;
        }

        public void reset() {
            bytes.reset();
            handles.setOut(bytes);
            handles.clear();
        }

        public BytesStreamOutput bytes() {
            return bytes;
        }

        public StreamOutput handles() throws IOException {
            return handles;
        }

        public StreamOutput bytes(Compressor compressor) throws IOException {
            return compressor.streamOutput(bytes);
        }

        public StreamOutput handles(Compressor compressor) throws IOException {
            StreamOutput compressed = compressor.streamOutput(bytes);
            handles.clear();
            handles.setOut(compressed);
            return handles;
        }
    }

    static class SoftWrapper<T> {
        private SoftReference<T> ref;

        public SoftWrapper() {
        }

        public void set(T ref) {
            this.ref = new SoftReference<T>(ref);
        }

        public T get() {
            return ref == null ? null : ref.get();
        }

        public void clear() {
            ref = null;
        }
    }

    private static final SoftWrapper<Queue<Entry>> cache = new SoftWrapper<Queue<Entry>>();
    private static final AtomicInteger counter = new AtomicInteger();
    public static int BYTES_LIMIT = 1 * 1024 * 1024; // don't cache entries that are bigger than that...
    public static int COUNT_LIMIT = 100;

    public static void clear() {
        cache.clear();
    }

    public static Entry popEntry() {
        Queue<Entry> ref = cache.get();
        if (ref == null) {
            return newEntry();
        }
        Entry entry = ref.poll();
        if (entry == null) {
            return newEntry();
        }
        counter.decrementAndGet();
        entry.reset();
        return entry;
    }

    public static void pushEntry(Entry entry) {
        entry.reset();
        if (entry.bytes().bytes().length() > BYTES_LIMIT) {
            return;
        }
        Queue<Entry> ref = cache.get();
        if (ref == null) {
            ref = new LinkedTransferQueue<Entry>();
            counter.set(0);
            cache.set(ref);
        }
        if (counter.incrementAndGet() > COUNT_LIMIT) {
            counter.decrementAndGet();
        } else {
            ref.add(entry);
        }
    }

    private static ThreadLocal<SoftReference<UTF8StreamWriter>> utf8StreamWriter = new ThreadLocal<SoftReference<UTF8StreamWriter>>();

    public static UTF8StreamWriter utf8StreamWriter() {
        SoftReference<UTF8StreamWriter> ref = utf8StreamWriter.get();
        UTF8StreamWriter writer = (ref == null) ? null : ref.get();
        if (writer == null) {
            writer = new UTF8StreamWriter(1024 * 4);
            utf8StreamWriter.set(new SoftReference<UTF8StreamWriter>(writer));
        }
        writer.reset();
        return writer;
    }
}

@@ -986,16 +986,114 @@
 mWriter;
+%0Aimport org.elasticsearch.common.unit.ByteSizeValue;%0Aimport org.elasticsearch.monitor.jvm.JvmInfo;
 %0A%0Aimport
@@ -3155,16 +3155,1153 @@
 T = 100;
+ // number of concurrent entries cached%0A%0A    static %7B%0A        // guess the maximum size per entry and the maximum number of entries based on the heap size%0A        long maxHeap = JvmInfo.jvmInfo().mem().heapMax().bytes();%0A        if (maxHeap %3C ByteSizeValue.parseBytesSizeValue(%22500mb%22).bytes()) %7B%0A            BYTES_LIMIT = (int) ByteSizeValue.parseBytesSizeValue(%22500kb%22).bytes();%0A            COUNT_LIMIT = 10;%0A        %7D else if (maxHeap %3C ByteSizeValue.parseBytesSizeValue(%221gb%22).bytes()) %7B%0A            BYTES_LIMIT = (int) ByteSizeValue.parseBytesSizeValue(%221mb%22).bytes();%0A            COUNT_LIMIT = 20;%0A        %7D else if (maxHeap %3C ByteSizeValue.parseBytesSizeValue(%224gb%22).bytes()) %7B%0A            BYTES_LIMIT = (int) ByteSizeValue.parseBytesSizeValue(%222mb%22).bytes();%0A            COUNT_LIMIT = 50;%0A        %7D else if (maxHeap %3C ByteSizeValue.parseBytesSizeValue(%2210gb%22).bytes()) %7B%0A            BYTES_LIMIT = (int) ByteSizeValue.parseBytesSizeValue(%225mb%22).bytes();%0A            COUNT_LIMIT = 50;%0A        %7D else %7B%0A            BYTES_LIMIT = (int) ByteSizeValue.parseBytesSizeValue(%2210mb%22).bytes();%0A            COUNT_LIMIT = 100;%0A        %7D%0A    %7D
 %0A%0A    pu

improve cached buffer allocation sizes based on jvm heap configured