001/*
002 * ModeShape (http://www.modeshape.org)
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *       http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.modeshape.common.collection.ring;
018
019import org.modeshape.common.annotation.NotThreadSafe;
020
021/**
022 * A consumer of entries that are added to the ring buffer. Note that consumers do not need to be threadsafe, since they are
023 * called from only a single thread in the ring buffer.
024 * 
025 * @param <T> the type of entry
026 * @see RingBuffer#addConsumer(Object)
027 * @see RingBuffer#addConsumer(Object, int)
028 * @author Randall Hauch (rhauch@redhat.com)
029 */
030@NotThreadSafe
031public abstract class Consumer<T> implements AutoCloseable {
032    /**
033     * Consume an entry from the ring buffer. All exceptions should be handled by the implementation.
034     * 
035     * @param entry the entry
036     * @param position the position of the entry in the ring buffer;
037     * @param maxPosition the maximum position that available in the ring buffer; in the case of a batch of entries, this may be
038     *        greater than position
039     * @return true if the consumer should continue processing the next entry, or false if this consumer should stop
040     */
041    public abstract boolean consume( T entry,
042                                     long position,
043                                     long maxPosition );
044
045    /**
046     * Called by the {@link RingBuffer} when the buffer has been shutdown and after this consumer's has
047     * {@link #consume(Object, long, long) consumed} all entries that remain in the now-closed buffer.
048     * <p>
049     * This method does nothing by default, but subclasses can override it to be notified when the consumer will not be called
050     * again and can clean up any resources.
051     * </p>
052     */
053    @Override
054    public void close() {
055        // do nothing by default
056    }
057
058}