/* * @(#) $Id: IoFuture.java 190262 2005-06-12 12:29:37Z trustin $ * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.mina.common; /** * Represents the result of an asynchronous I/O operation. * * @author The Apache Directory Project * @version $Rev: 190262 $, $Date: 2005-06-12 13:29:37 +0100 (Sun, 12 Jun 2005) $ */ public class IoFuture { private Object result; private boolean ready; private Callback callback; /** * Something interested in being notified when the result * of an IoFuture becomes available */ public interface Callback { /** * Invoked when the result of an IoFuture * becomes available * * @param result The result */ public void resultReady(Object result); } /** * Creates a new instance. */ protected IoFuture() { } /** * Wait for the asynchronous operation to end. */ public synchronized void join() { while( !ready ) { try { wait(); } catch( InterruptedException e ) { } } } /** * Wait for the asynchronous operation to end with the specified timeout. * * @return true if the operation is finished. */ public synchronized boolean join( long timeoutInMillis ) { long startTime = ( timeoutInMillis <= 0 ) ? 0 : System .currentTimeMillis(); long waitTime = timeoutInMillis; if( ready ) { return ready; } else if( waitTime <= 0 ) { return ready; } for( ;; ) { try { wait( waitTime ); } catch( InterruptedException e ) { } if( ready ) return true; else { waitTime = timeoutInMillis - ( System.currentTimeMillis() - startTime ); if( waitTime <= 0 ) { return ready; } } } } /** * Returns if the asynchronous operation is finished. */ public synchronized boolean isReady() { return ready; } /** * Sets a Callback to be notified when a result * becomes available. * If this IoFutures result has already become obtained, * the specified callback is notified immediately * * @param callback The callback */ public synchronized void setCallback(Callback callback) { this.callback = callback; if (ready) { callback.resultReady(result); } } /** * Sets the result of the asynchronous operation, and mark it as finished. * If this future is associated with a Callback, the callback * is notified of the new value */ protected synchronized void setValue( Object newValue ) { result = newValue; ready = true; if (callback != null) { callback.resultReady(result); } notifyAll(); } /** * Returns the result of the asynchronous operation. */ protected synchronized Object getValue() { return result; } }