net.sf.asyncobjects
Class Using<S extends ACloseable,T>

java.lang.Object
  extended by net.sf.asyncobjects.Using<S,T>
Type Parameters:
S - Service type
T - Result type
All Implemented Interfaces:
ExplicitSharing

public abstract class Using<S extends ACloseable,T>
extends Object
implements ExplicitSharing

This is an utility class that executes some action and than closes resource that implements the interface ACloseable after activity in the body finishes.

The sample below gets output stream of the socket, writes 1,2,3 to it and closes it. The promise returned from method resolves only after output is closed.

 
      private Promise<Void> write123(ASocket socket) {
        return new Using<AByteOutput,Void>(socket.getOutput()) {
                protected Promise<Void> run(AByteOutput out) {
             // send data, result promise will resolve when data finish writing.
             // The close method on output will be called only after it rather
             // then right after return of the method.
             return out.write(BinaryData.fromBytes(new byte[]{(byte)1,byte)2,byte)3})); 
           }
        }.promise();
      }
 
 


Constructor Summary
Using(Promise<S> servicePromise)
          A constructor
Using(S service)
          A constructor
 
Method Summary
protected  Promise<? extends T> openFailed(Throwable problem)
          This method is called in separate turn in case when open operation failed.
 Promise<T> promise()
           
protected abstract  Promise<? extends T> run(S service)
          This method should be implemented by subclasses.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Using

public Using(Promise<S> servicePromise)
A constructor

Parameters:
servicePromise - a promise for service

Using

public Using(S service)
A constructor

Parameters:
service - a service proxy
Method Detail

run

protected abstract Promise<? extends T> run(S service)
This method should be implemented by subclasses.

Parameters:
service - a service that was argument of constructor
Returns:
a promise for OutType or result of OutType.

openFailed

protected Promise<? extends T> openFailed(Throwable problem)
                                   throws Throwable
This method is called in separate turn in case when open operation failed.

Parameters:
problem - a problem
Returns:
a result value will be used as result of using operation.
Throws:
Throwable - a problem

promise

public final Promise<T> promise()
Returns:
a result promise. it resolves after the body is finished and after close operation is complete. Note that if close() operation is smashed, the result promise will be smashed with problem of close operation independently of what was the result of run(ACloseable).


Copyright © 2002-2007 Constantine Plotnikov. All Rights Reserved.