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

com.fasterxml.sort.util.BlockingQueueReader Maven / Gradle / Ivy

There is a newer version: 1.1.0
Show newest version
package com.fasterxml.sort.util;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.BlockingQueue;

import com.fasterxml.sort.DataReader;

/**
 * Base implementation for {@link DataReader} that uses a
 * {@link BlockingQueue} for getting input.
 * The only missing part is implementation for
 * {@link #estimateSizeInBytes(Object)}, since there is no way
 * to provide a meaningful estimate without knowing object type.
 */
public abstract class BlockingQueueReader
    extends DataReader
{
    protected final BlockingQueue _queue;
    
    protected final E _endMarker;

    protected boolean _closed;

    @Deprecated
    public BlockingQueueReader(BlockingQueue q) {
        this(q, null);
    }
    
    /**
     * @param q Queue to read entries from
     * @param endMarker Value that is used to signal end-of-input; when this value
     *   is gotten from queue, reader assumes that no more input is coming and
     *   will return null from {@link #readNext}.
     */
    public BlockingQueueReader(BlockingQueue q, E endMarker) {
        _queue = q;
        _endMarker = endMarker;
    }
    
    @Override
    public void close() throws IOException {
        _closed = true;
    }

    @Override
    public abstract int estimateSizeInBytes(E item);

    @Override
    public E readNext() throws IOException {
        if (_closed) {
            return null;
        }
        try {
            E value = _queue.take();
            if (value == _endMarker) {
                _closed = true;
                return null;
            }
            return value;
        } catch (InterruptedException e) {
            InterruptedIOException ie = new InterruptedIOException();
            ie.initCause(e);
            throw ie;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy