001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2016-2018 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.io.util;
020
021/**
022 * Defines the method of a buffer collector.
023 *
024 * @param <B> the type of buffer that can be collected
025 */
026public interface BufferCollector<B extends ManagedBuffer<?>> {
027
028    /**
029     * A predefined buffer collector that does nothing when the managed buffer
030     * is no longer used. Using this collector with a managed buffer
031     * effectively make it an unmanaged buffer.
032     */
033    BufferCollector<? extends ManagedBuffer<?>> NOOP_COLLECTOR
034        = new BufferCollector<>() {
035            @Override
036            public void recollect(ManagedBuffer<?> buffer) {
037                // Does nothing.
038            }
039        };
040
041    /**
042     * A type-safe way to get the {@link #NOOP_COLLECTOR}.
043     *
044     * @param <T> the type of buffer that can be collected
045     * @return the noop buffer collector
046     */
047    @SuppressWarnings("unchecked")
048    static <T extends ManagedBuffer<?>> BufferCollector<T>
049            noopCollector() {
050        return (BufferCollector<T>) NOOP_COLLECTOR;
051    }
052
053    /**
054     * Recollect the buffer. Invoked after all locks to a managed buffer
055     * have been released. Usually, the implementation of a buffer collector
056     * returns the buffer into some kind of pool when this method is invoked.
057     * 
058     * @param buffer the buffer
059     */
060    void recollect(B buffer);
061
062}