org.refcodes.io.AbstractPrefetchInputStreamReceiver Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of refcodes-io Show documentation
Show all versions of refcodes-io Show documentation
Artifact with commonly used I/O functionality and for connection related
issues such as receiving or transmitting data in a unified way.
// /////////////////////////////////////////////////////////////////////////////
// REFCODES.ORG
// =============================================================================
// This code is copyright (c) by Siegfried Steiner, Munich, Germany, distributed
// on an "AS IS" BASIS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, and licen-
// sed under the following (see "http://en.wikipedia.org/wiki/Multi-licensing")
// licenses:
// =============================================================================
// GNU General Public License, v3.0 ("http://www.gnu.org/licenses/gpl-3.0.html")
// together with the GPL linking exception applied; as being applied by the GNU
// Classpath ("http://www.gnu.org/software/classpath/license.html")
// =============================================================================
// Apache License, v2.0 ("http://www.apache.org/licenses/TEXT-2.0")
// =============================================================================
// Please contact the copyright holding author(s) of the software artifacts in
// question for licensing issues not being covered by the above listed licenses,
// also regarding commercial licensing models or regarding the compatibility
// with other open source licenses.
// /////////////////////////////////////////////////////////////////////////////
package org.refcodes.io;
import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.refcodes.component.ConnectionOpenable;
import org.refcodes.component.ConnectionStatus;
import org.refcodes.component.ConnectionComponent.ConnectionAutomaton;
import org.refcodes.controlflow.ControlFlowUtility;
import org.refcodes.controlflow.RetryTimeout;
import org.refcodes.data.DaemonLoopSleepTime;
import org.refcodes.data.RetryLoopCount;
import org.refcodes.mixin.Disposable;
/**
* Abstract implementation of the {@link DatagramsReceiver} interface. As of the
* prefetching functionality, a separate daemon thread (retrieved via an
* {@link ExecutorService}) reads from the provided {@link InputStream} and
* places the datagrams into a datagram queue until the datagram queue's
* capacity is reached. If the queue is empty, then the {@link #receive()} (
* {@link #receiveAll()}) method is blocked until the daemon thread places new
* datagrams into the queue. See also {@link AbstractDatagramsReceiver}.
*
* @param The type of the datagram to be operated with.
*/
public abstract class AbstractPrefetchInputStreamReceiver extends AbstractDatagramsReceiver {
// /////////////////////////////////////////////////////////////////////////
// STATICS:
// /////////////////////////////////////////////////////////////////////////
private static final Logger LOGGER = Logger.getLogger( AbstractPrefetchInputStreamReceiver.class.getName() );
// /////////////////////////////////////////////////////////////////////////
// VARIABLES:
// /////////////////////////////////////////////////////////////////////////
private ObjectInputStream _objectInputStream = null;
private ExecutorService _executorService;
private IoStreamReceiverDaemon _ioStreamReceiverDaemon = null;
private boolean _isDaemonAlive = false;
// /////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS:
// /////////////////////////////////////////////////////////////////////////
/**
* Creates an {@link AbstractPrefetchInputStreamReceiver}.
*/
public AbstractPrefetchInputStreamReceiver() {
this( DATAGRAM_QUEUE_SIZE, null );
}
/**
* Creates an {@link AbstractPrefetchInputStreamReceiver} using the given
* {@link ExecutorService} required for thread generation in an JEE
* environment.
*
* @param aExecutorService The {@link ExecutorService} to be used, when null
* then an {@link ExecutorService} something line
* {@link Executors#newCachedThreadPool()} is then retrieved.
*/
public AbstractPrefetchInputStreamReceiver( ExecutorService aExecutorService ) {
this( DATAGRAM_QUEUE_SIZE, aExecutorService );
}
/**
* Creates an {@link AbstractPrefetchInputStreamReceiver} using the given
* datagram queue capacity.
*
* @param aQueueCapacity The capacity of the prefetch queue before it blocks
* until data is read via {@link #receive()} (
* {@link #receiveAll()}).
*/
public AbstractPrefetchInputStreamReceiver( int aQueueCapacity ) {
this( aQueueCapacity, null );
}
/**
* Creates an {@link AbstractPrefetchInputStreamReceiver} using the given
* {@link ExecutorService} required for thread generation in an JEE
* environment.
*
* @param aQueueCapacity The capacity of the prefetch queue before it blocks
* until data is read via {@link #receive()} (
* {@link #receiveAll()}).
* @param aExecutorService The {@link ExecutorService} to be used, when null
* then an {@link ExecutorService} something line
* {@link Executors#newCachedThreadPool()} is then retrieved.
*/
public AbstractPrefetchInputStreamReceiver( int aQueueCapacity, ExecutorService aExecutorService ) {
if ( aExecutorService == null ) {
_executorService = ControlFlowUtility.createCachedExecutorService( true );
}
else {
_executorService = ControlFlowUtility.toManagedExecutorService( aExecutorService );
}
}
// /////////////////////////////////////////////////////////////////////////
// METHODS:
// /////////////////////////////////////////////////////////////////////////
/**
* {@inheritDoc}
*/
@Override
public synchronized void close() throws IOException {
if ( !isClosed() ) {
super.close();
if ( _ioStreamReceiverDaemon != null ) {
_ioStreamReceiverDaemon.dispose();
_ioStreamReceiverDaemon = null;
}
try {
if ( _objectInputStream != null ) {
_objectInputStream.close();
}
}
catch ( IOException e ) {
throw new IOException( "Unable to close receiver (connection status is <" + getConnectionStatus() + ">) as of a causing exception <" + e.getClass().getName() + "> !", e );
}
}
}
// /////////////////////////////////////////////////////////////////////////
// HOOKS:
// /////////////////////////////////////////////////////////////////////////
/**
* Open, see also {@link ConnectionOpenable#open(Object)}.
*
* @param aInputStream the input stream
*
* @throws IOException the open exception
*/
protected synchronized void open( InputStream aInputStream ) throws IOException {
if ( isOpened() ) {
throw new IOException( "Unable to open the connection is is is already OPEN (connection status is <" + getConnectionStatus() + ">)." );
}
try {
if ( !( aInputStream instanceof BufferedInputStream ) ) {
_objectInputStream = new SerializableObjectInputStream( new BufferedInputStream( aInputStream ) );
}
else {
_objectInputStream = new SerializableObjectInputStream( aInputStream );
}
}
catch ( IOException aException ) {
if ( !isThrownAsOfAlreadyClosed( aException ) ) {
throw new IOException( "Unable to open the I/O stream receiver as of a causing exception.", aException );
}
}
_ioStreamReceiverDaemon = new IoStreamReceiverDaemon();
// LOGGER.debug( "Starting I/O stream receiver daemon <" + _ioStreamReceiverDaemon.getClass().getName() + ">." );
// Open the connection before daemon starts as daemon tests for an open connection:
setConnectionStatus( ConnectionStatus.OPENED );
_executorService.execute( _ioStreamReceiverDaemon );
if ( !_isDaemonAlive ) {
final RetryTimeout theRetryTimeout = new RetryTimeout( DaemonLoopSleepTime.NORM.getTimeMillis(), RetryLoopCount.NORM_NUM_RETRY_LOOPS.getValue() );
while ( !_isDaemonAlive ) {
theRetryTimeout.nextRetry();
}
}
}
/**
* Checks if is openable. See also
* {@link ConnectionAutomaton#isOpenable(Object)}.
*
* @param aInputStream the input stream
*
* @return true, if is openable
*/
protected boolean isOpenable( InputStream aInputStream ) {
return aInputStream == null ? false : !isOpened();
}
// /////////////////////////////////////////////////////////////////////////
// INNER CLASSES:
// /////////////////////////////////////////////////////////////////////////
/**
* The {@link IoStreamReceiverDaemon} waits for datagrams and puts them into
* the queue.
*/
private class IoStreamReceiverDaemon implements Runnable, Disposable {
private boolean _isDisposed = false;
// /////////////////////////////////////////////////////////////////////
// DAEMON:
// /////////////////////////////////////////////////////////////////////
@SuppressWarnings("unchecked")
@Override
public void run() {
try {
Object eObject = null;
_isDaemonAlive = true;
while ( !_isDisposed && isOpened() ) {
try {
eObject = _objectInputStream.readObject();
pushDatagram( (DATA) eObject );
}
catch ( ClassNotFoundException | ClassCastException e ) {
LOGGER.log( Level.WARNING, "Unable to read datagram from sender (connection status is <" + getConnectionStatus() + ">) as of a causing exception <" + e.getClass().getName() + "> !", e );
}
}
}
catch ( IOException | InternalError e1 ) {
synchronized ( AbstractPrefetchInputStreamReceiver.this ) {
if ( AbstractPrefetchInputStreamReceiver.this.isOpened() ) {
try {
if ( !( e1 instanceof EOFException ) ) {
LOGGER.log( Level.WARNING, "Unable to read datagram from sender (connection status is a" + getConnectionStatus() + ">) as of a causing exception <" + e1.getClass().getName() + ">!", e1 );
}
close();
}
catch ( IOException e2 ) {
LOGGER.log( Level.WARNING, "Unable to close malfunctioning connection as of as of a causing exception <" + e2.getClass().getName() + ">!", e2 );
}
}
}
}
finally {
_isDaemonAlive = false;
// LOGGER.log( Level.WARNING, "Terminating I/O stream receiver daemon <" + IoStreamReceiverDaemon.this.getClass().getName() + ">." );
}
}
/**
* Dispose.
*/
@Override
public void dispose() {
_isDisposed = true;
}
}
}