All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.xerial.snappy.buffer.CachedBufferAllocator Maven / Gradle / Ivy

Go to download

Easy Redis Java client and Real-Time Data Platform. Valkey compatible. Sync/Async/RxJava3/Reactive API. Client side caching. Over 50 Redis based Java objects and services: JCache API, Apache Tomcat, Hibernate, Spring, Set, Multimap, SortedSet, Map, List, Queue, Deque, Semaphore, Lock, AtomicLong, Map Reduce, Bloom filter, Scheduler, RPC

There is a newer version: 3.40.2
Show newest version
package org.xerial.snappy.buffer;

import java.lang.ref.SoftReference;
import java.util.*;

/**
 * Cached buffer
 */
public class CachedBufferAllocator
        implements BufferAllocator
{
    private static BufferAllocatorFactory factory = new BufferAllocatorFactory()
    {
        @Override
        public BufferAllocator getBufferAllocator(int bufferSize)
        {
            return CachedBufferAllocator.getAllocator(bufferSize);
        }
    };

    public static void setBufferAllocatorFactory(BufferAllocatorFactory factory)
    {
        assert (factory != null);
        CachedBufferAllocator.factory = factory;
    }

    public static BufferAllocatorFactory getBufferAllocatorFactory()
    {
        return factory;
    }

    /**
     * Use SoftReference so that having this queueTable does not prevent the GC of CachedBufferAllocator instances
     */
    private static final Map> queueTable = new HashMap>();

    private final int bufferSize;
    private final Deque bufferQueue;

    public CachedBufferAllocator(int bufferSize)
    {
        this.bufferSize = bufferSize;
        this.bufferQueue = new ArrayDeque();
    }

    public static synchronized CachedBufferAllocator getAllocator(int bufferSize)
    {
        CachedBufferAllocator result = null;

        if (queueTable.containsKey(bufferSize)) {
            result = queueTable.get(bufferSize).get();
        }
        if (result == null) {
            result = new CachedBufferAllocator(bufferSize);
            queueTable.put(bufferSize, new SoftReference(result));
        }
        return result;
    }

    @Override
    public byte[] allocate(int size)
    {
        synchronized (this) {
            if (bufferQueue.isEmpty()) {
                return new byte[size];
            }
            else {
                return bufferQueue.pollFirst();
            }
        }
    }

    @Override
    public void release(byte[] buffer)
    {
        synchronized (this) {
            bufferQueue.addLast(buffer);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy