
com.gc.iotools.stream.is.ReadAheadInputStream Maven / Gradle / Ivy
Show all versions of easystream Show documentation
package com.gc.iotools.stream.is;
/*
* Copyright (c) 2008, 2015 Gabriele Contini. This source code is released
* under the BSD License.
*/
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.ExecutorService;
import org.apache.commons.io.IOUtils;
import com.gc.iotools.stream.base.ExecutionModel;
import com.gc.iotools.stream.base.ExecutorServiceFactory;
/**
*
* This class tries to read the InputStream
passed as a parameter
* in a memory buffer, thus improving the reading performances.
*
*
* This can speed up reading when the time spent in reading from the stream is
* same order as the time spent in elaborating the stream, because it decouples
* the reading process and the elaboration in two different threads putting them
* in parallel.
*
*
* Sample Usage:
*
*
* InputStream source = ... some slow InputStream.
* InputStream fastIs = new ReadAheadInputStream(source);
* //use here fastIs instead of the source InputStream
* ...
* fastIs.close();
*
*
*
* @author dvd.smnt
* @since 1.2.6
* @version $Id: ReadAheadInputStream.java 527 2014-02-24 19:29:50Z
* $
*/
public class ReadAheadInputStream extends InputStreamFromOutputStream {
private final InputStream source;
/**
*
* Constructor for ReadAheadInputStream.
*
*
* @param source
* a {@link java.io.InputStream} object.
*/
public ReadAheadInputStream(final InputStream source) {
this(source, -1);
}
/**
*
* Constructor for ReadAheadInputStream.
*
*
* @param source
* a {@link java.io.InputStream} object.
* @param bufferSize
* a int.
*/
public ReadAheadInputStream(final InputStream source, final int bufferSize) {
this(source, bufferSize, ExecutionModel.THREAD_PER_INSTANCE);
}
/**
*
* Constructor for ReadAheadInputStream.
*
*
* @param source
* a {@link java.io.InputStream} object.
* @param bufferSize
* a int.
* @param executionModel
* a {@link com.gc.iotools.stream.base.ExecutionModel} object.
*/
public ReadAheadInputStream(final InputStream source, final int bufferSize,
final ExecutionModel executionModel) {
this(source, bufferSize, ExecutorServiceFactory
.getExecutor(executionModel));
}
/**
*
* Constructor for ReadAheadInputStream.
*
*
* @param source
* a {@link java.io.InputStream} object.
* @param bufferSize
* a int.
* @param executorService
* a {@link java.util.concurrent.ExecutorService} object.
*/
public ReadAheadInputStream(final InputStream source, final int bufferSize,
final ExecutorService executorService) {
// 256K buffer by default
super(false, executorService, (bufferSize > 0 ? bufferSize
: (65536 * 4)));
this.source = source;
}
/** {@inheritDoc} */
@Override
protected Void produce(final OutputStream sink) throws Exception {
IOUtils.copy(this.source, sink);
this.source.close();
return null;
}
}