com.twitter.util.Disposable represents a live resource that must be disposed after use.
com.twitter.util.Managed is a factory for creating and composing such resources.
Managed resources are composed together so their lifetimes are synchronized.
The following example shows how to build and use composite managed resources:
// Create managed Tracerdef mkManagedTracer() = new Managed[Tracer] {
def make() = new Disposable[Tracer] {
val underlying = new Tracer()
def get = underlying
def dispose(deadline: Time) = underlying.close() // assumes Tracer uses relese() to manage lifetime
}
}
// Create managed Server using Tracer as dependencydef mkManagedServer(t: Tracer) = new Managed[Server] {
def make() = new Disposable[Server] {
val underlying = new Server(t) // Server requires tracer to be createddef get = underlying
def dispose(deadline: Time) = underlying.close() // assumes Server uses close() to manage lifetime
}
}
// Create composite resourceval compRes: Managed[Server] = for {
a <- mkManagedTracer()
b <- mkManagedServer(a)
} yield b
// Use composite resource in safe fashion. It's guaranteed that both resources// will be properly closed/released when done using them.
compRes foreach { b =>// use b (which is type Server in this case)
} // dispose called on both resources
Disposable/Managed Semantics
com.twitter.util.Disposable: get can be called multiple times and should return same instance;
dispose can be called only once and should release resource that get is returning;
calling get after dispose is undefined.
com.twitter.util.Managed: multiple calls to make could return
a) new instance or
b) ref counted instance of the underlying resource or
c) same instance when resource doesn't need to be actually disposed, etc.
Disposable is a container for a resource that must be explicitly disposed when
no longer needed. After this, the resource is no longer available.
Resource Management
com.twitter.util.Disposable represents a live resource that must be disposed after use. com.twitter.util.Managed is a factory for creating and composing such resources. Managed resources are composed together so their lifetimes are synchronized.
The following example shows how to build and use composite managed resources:
Disposable/Managed Semantics
com.twitter.util.Disposable: get can be called multiple times and should return same instance; dispose can be called only once and should release resource that get is returning; calling get after dispose is undefined.
com.twitter.util.Managed: multiple calls to make could return a) new instance or b) ref counted instance of the underlying resource or c) same instance when resource doesn't need to be actually disposed, etc.
Disposable is a container for a resource that must be explicitly disposed when no longer needed. After this, the resource is no longer available.