Packages

package util

Ordering
  1. Alphabetic
Visibility
  1. Public
  2. Protected

Package Members

  1. package jackson
  2. package javainterop
  3. package lint
  4. package logging
  5. package mock
  6. package reflect
  7. package registry
  8. package routing
  9. package security
  10. package testing
  11. package tunable
  12. package validation

Type Members

  1. abstract class AbstractClosable extends Closable

    Abstract Closable class for Java compatibility.

  2. abstract class AbstractClosableOnce extends ClosableOnce

    A Java-friendly API for the ClosableOnce trait.

  3. abstract class AbstractCloseAwaitably extends AbstractClosable with Awaitable[BoxedUnit]

    Java's analog of Scala's com.twitter.util.CloseAwaitably.

    Java's analog of Scala's com.twitter.util.CloseAwaitably.

    In order to make it more Java-friendly, the abstract method com.twitter.util.AbstractCloseAwaitably#onClose is used instead of a higher-order function in Scala version.

    An example usage looks as follows.

    
    
      class A extends AbstractCloseAwaitably {
        public Future onClose(Time deadline) {
          return Future.Done();
        
      }
    
    }
    

  4. abstract class AbstractEvent[T] extends Event[T]

    Abstract Event class for Java compatibility.

  5. abstract class AbstractMonitor extends Monitor

    An API for creating Monitor instances in Java.

  6. abstract class AbstractVar[T] extends Var[T]

    Abstract Var class for Java compatibility.

  7. abstract class AbstractWitness[T] extends Witness[T]

    Abstract Witness class for Java compatibility.

  8. final class Activities extends AnyRef

    A Java adaptation of com.twitter.util.Activity companion object.

  9. case class Activity[+T](run: Var[State[T]]) extends Product with Serializable

    Activity, like Var, is a value that varies over time; but, richer than Var, these values have error and pending states.

    Activity, like Var, is a value that varies over time; but, richer than Var, these values have error and pending states. They are useful for modeling a process that produces values, but also intermittent failures (e.g. address resolution, reloadable configuration).

    As such, an Activity can be in one of three states:

    • Pending: output is pending;
    • Ok: an output is available; and
    • Failed: the process failed with an exception.

    An Activity may transition between any state at any time. They are typically constructed from Events, but they can also be constructed without arguments.

    val (activity, witness) = Activity[Int]()
    println(activity.sample()) // throws java.lang.IllegalStateException: Still pending

    As you can see, Activities start in a Pending state. Attempts to sample an Activity that is pending will fail. Curiously, the constructor for an Activity also returns a Witness.

    Recall that a Witness is the interface to something that you can send values to; and in this case, that something is the Activity.

    witness.notify(Return(1))
    println(activity.sample()) // prints 1

    (For implementers, it may be useful to think of Activity as a monad transformer for an Op monad over Var where Op is like a Try with an additional pending state.)

  10. trait Awaitable[+T] extends AnyRef

    Wait for the result of some action.

    Wait for the result of some action. Awaitable is not used directly, but through the Await object.

  11. trait Base64StringEncoder extends StringEncoder

    A utility for encoding strings and byte arrays to a MIME base64 string, and decoding from strings encoded in MIME base64 to byte arrays.

    A utility for encoding strings and byte arrays to a MIME base64 string, and decoding from strings encoded in MIME base64 to byte arrays.

    The encoding for strings is UTF-8.

  12. trait Base64UrlSafeStringEncoder extends StringEncoder

    A utility for encoding strings and byte arrays to a URL-safe base64 string, and decoding from strings encoded in base64 to byte arrays.

    A utility for encoding strings and byte arrays to a URL-safe base64 string, and decoding from strings encoded in base64 to byte arrays.

    The encoding for strings is UTF-8.

  13. class Batcher[In, Out] extends (In) => Future[Out]

    Provides an interface for working with a batched com.twitter.util.Future

  14. class BinaryThriftCodec[T <: TBase[_, _]] extends ThriftCodec[T, Factory]
  15. class BinaryThriftSerializer extends ThriftSerializer with Base64StringEncoder

    A thread-safe ThriftSerializer that uses TBinaryProtocol.

    A thread-safe ThriftSerializer that uses TBinaryProtocol.

    Note

    an implementation using com.twitter.finagle.thrift.Protocols.binaryFactory instead of this is recommended.

  16. trait Cancellable extends AnyRef

    Defines a trait that makes the underlying object *cancellable*.

    Defines a trait that makes the underlying object *cancellable*. Cancellable objects may be linked to each other (one way) in order to propagate cancellation.

    Note that the underlying object may or may not _respond_ to the cancellation request. That is, calling 'cancel()' does not guarantee the cancellation of the computation; rather it is a hint that the provider of the computation may choose to ignore.

  17. class CancellableSink extends Cancellable
  18. trait Closable extends AnyRef

    Closable is a mixin trait to describe a closable resource.

    Closable is a mixin trait to describe a closable resource.

    Note: There is a Java-friendly API for this trait: com.twitter.util.AbstractClosable.

  19. trait ClosableOnce extends Closable with CloseOnce

    A mixin trait to describe resources that are an idempotent Closable.

    A mixin trait to describe resources that are an idempotent Closable.

    The first call to close(Time) triggers closing the resource with the provided deadline while subsequent calls will yield the same Future as the first invocation irrespective of the deadline provided.

    See also

    CloseOnce if you are mixing in or extending an existing Closable to prevent any "inherits from conflicting members" compile-time issues.

  20. final class Closables extends AnyRef

    Java compatibility layer for com.twitter.util.Closable.

  21. trait CloseAwaitably extends CloseAwaitably0[Unit]

    A mixin to make an com.twitter.util.Awaitable out of a com.twitter.util.Closable.

    A mixin to make an com.twitter.util.Awaitable out of a com.twitter.util.Closable.

    Use closeAwaitably in the definition of close:

    class MyClosable extends Closable with CloseAwaitably {
      def close(deadline: Time) = closeAwaitably {
        // close the resource
      }
    }

    Note: There is a Java-friendly API for this trait: com.twitter.util.AbstractCloseAwaitably.

  22. trait CloseOnce extends Closable

    A mixin trait to describe resources that are an idempotent Closable.

    A mixin trait to describe resources that are an idempotent Closable.

    The first call to close(Time) triggers closing the resource with the provided deadline while subsequent calls will yield the same Future as the first invocation irrespective of the deadline provided.

    Note

    this mixin extends Closable as a workaround for extending AbstractClosableOnce in Java. The mixin's final override is not recognized when compiled with Scala 3. See CSL-11187 or https://github.com/lampepfl/dotty/issues/13104.

    See also

    ClosableOnce if you are not mixing in or extending an existing Closable

    ClosableOnce.of for creating a proxy to a Closable that has already been instantiated.

  23. trait CloseOnceAwaitably extends CloseOnceAwaitably0[Unit]

    A mixin to make an com.twitter.util.Awaitable out of a com.twitter.util.ClosableOnce.

    A mixin to make an com.twitter.util.Awaitable out of a com.twitter.util.ClosableOnce.

    class MyClosable extends ClosableOnce with CloseOnceAwaitably {
      def closeOnce(deadline: Time) = {
        // close the resource
      }
    }
  24. trait Codec[T, S] extends Encoder[T, S] with Decoder[T, S]

    A base trait for all Codecs that translate a type T into a serialized form S

  25. abstract class Command[-T1] extends (T1) => Unit
  26. class CompactThriftCodec[T <: TBase[_, _]] extends ThriftCodec[T, Factory]
  27. class CompactThriftSerializer extends ThriftSerializer with Base64StringEncoder

    A thread-safe ThriftSerializer that uses TCompactProtocol.

  28. class ConstFuture[A] extends Future[A]

    A Future that is already completed.

    A Future that is already completed.

    These are cheap in construction compared to Promises.

  29. class ConstVar[T] extends Var[T] with Extractable[T]

    A constant Extractable Var on v.

  30. trait Decoder[T, S] extends AnyRef

    A base trait for decoders for type T from a serialized form S

  31. trait DecoderCompanion extends AnyRef
  32. trait Diff[CC[_], T] extends AnyRef

    A Diff stores the necessary instructions required to bring two version of a data structure into agreement.

  33. trait Diffable[CC[_]] extends AnyRef

    A type class that tells how to compute a Diff between two versions of a collection CC[T].

  34. trait Disposable[+T] extends AnyRef

    com.twitter.util.Disposable represents a live resource that must be disposed after use.

    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:

    // Create managed Tracer
    def 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 dependency
    def mkManagedServer(t: Tracer) = new Managed[Server] {
      def make() = new Disposable[Server] {
        val underlying = new Server(t) // Server requires tracer to be created
        def get = underlying
        def dispose(deadline: Time) = underlying.close() // assumes Server uses close() to manage lifetime
      }
    }
    
    // Create composite resource
    val 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.

  35. class DoubleTrouble extends Exception
  36. sealed class Duration extends TimeLike[Duration] with Serializable

    A Duration represents the span between two points in time.

    A Duration represents the span between two points in time. It represents this with a signed long, and thus the largest representable duration is:

    106751.days+23.hours+47.minutes+16.seconds +854.milliseconds+775.microseconds+807.nanoseconds

    Durations may be constructed via its companion object, Duration.fromNanoseconds, Duration.fromSeconds, etc. or by using the time conversions:

    import com.twitter.conversions.DurationOps._
    
    3.days+4.nanoseconds

    In addition to the timespans in the range of Long.MinValue to Long.MaxValue nanoseconds, durations have two distinguished values: Duration.Top and Duration.Bottom. These have special semantics: Top is greater than every other duration, save for itself; Bottom is smaller than any duration except for itself — they act like positive and negative infinity, and their arithmetic follows. This is useful for representing durations that are truly infinite; for example the absence of a timeout.

  37. trait Encoder[T, S] extends (T) => S

    A base trait for encoders of type T into a serialized form S

  38. trait EncoderCompanion extends AnyRef
  39. trait Event[+T] extends AnyRef

    Events are emitters of values.

    Events are emitters of values. They can be processed as if they were streams. Here's how to create one that emits Ints.

    val ints = Event[Int]()

    To listen to an Event stream for values, register a handler.

    val you = ints.respond { n => println(s"$n for you") }

    Handlers in Event-speak are called Witnesses. And, respond is equivalent to register(Witness { ... }), so we can also write:

    val me = ints.register(Witness { n => println(s"$n for me") })

    Registration is time-sensitive. Witnesses registered to an Event stream can't observe past values. In this way, Events are instantaneous. When the stream emits a value, it fans out to every Witness; if there are no Witnesses to that communication, whatever value it carried is lost.

    Events emit values, okay, but who decides what is emitted? The implementor of an Event decides!

    But there's another way: you can create an Event that is also a Witness. Remember, Witnesses are simply handlers that can receive a value. Their type is T => Unit. So an Event that you can send values to is also a Witness.

    The ints Event we created above is one of these. Watch:

    scala> ints.notify(1)
    1 for you
    1 for me

    We can also stop listening. This is important for resource cleanup.

    scala> me.close()
    scala> ints.notify(2)
    2 for you

    In relation to Vars, Events are instantaneous values, defined only at particular instants in time; whereas Vars are defined at all times. It is possible to view Events as the discrete counterpart to Var's continuous nature.

    Note: There is a Java-friendly API for this trait: com.twitter.util.AbstractEvent.

  40. final class Events extends AnyRef

    A Java adaptation of com.twitter.util.Event companion object.

  41. abstract class ExceptionalFunction[-T1, +R] extends Function[T1, R]
  42. abstract class ExceptionalFunction0[+R] extends Function0[R]
  43. class ExecutorServiceFuturePool extends FuturePool

    A FuturePool implementation backed by an java.util.concurrent.ExecutorService.

    A FuturePool implementation backed by an java.util.concurrent.ExecutorService.

    If a piece of work has started, it cannot be cancelled and will not propagate cancellation unless interruptible is true. If you want to propagate cancellation, use an InterruptibleExecutorServiceFuturePool.

  44. trait Extractable[T] extends AnyRef
  45. abstract class FactoryPool[A] extends Pool[A]
  46. abstract class Function[-T1, +R] extends PartialFunction[T1, R]

    This class is for Java friendliness.

    This class is for Java friendliness. Any Scala method that takes Function1[A, B] can now take a Function[A, B]. Because Function1 is a trait, it is very difficult to instantiate directly in Java.

  47. abstract class Function0[+R] extends () => R
  48. abstract class Function2[-T1, -T2, +R] extends (T1, T2) => R
  49. abstract class Function3[-T1, -T2, -T3, +R] extends (T1, T2, T3) => R
  50. abstract class Future[+A] extends Awaitable[A]

    Represents an asynchronous value.

    Represents an asynchronous value.

    See the user guide on concurrent programming with Futures to better understand how they work and can be used.

    A Future[T] can be in one of three states:

    • Pending, the computation has not yet completed
    • Satisfied successfully, with a result of type T (a Return)
    • Satisfied by a failure, with a Throwable result (a Throw)

    This definition of Future does not assume any concrete implementation; in particular, it does not couple the user to a specific executor or event loop.

    See also

    The user guide on concurrent programming with Futures.

    Futures for Java-friendly APIs.

  51. class FutureCancelledException extends Exception
  52. trait FutureEventListener[T] extends AnyRef

    A Java friendly API for handling side-effects for a Future.

    A Java friendly API for handling side-effects for a Future.

    If you want a Java API to sequence the work you can use a FutureTransformer.

    See also

    Future.respond which is the equivalent Scala API for further details.

    Future.addEventListener for using it with a Future.

    FutureTransformer for a Java API for transforming the results of Futures.

  53. class FutureNonLocalReturnControl extends Exception
  54. trait FuturePool extends AnyRef

    A FuturePool executes tasks asynchronously, typically using a pool of worker threads.

  55. class FuturePools extends AnyRef

    A Java adaptation of the com.twitter.util.FuturePool companion object.

  56. class FutureTask[A] extends Promise[A] with Runnable
  57. abstract class FutureTransformer[-A, +B] extends AnyRef

    An alternative interface for performing Future transformations; that is, converting a Future[A] to a Future[B].

    An alternative interface for performing Future transformations; that is, converting a Future[A] to a Future[B]. This interface is designed to be friendly to Java users since it does not require creating many small Function objects. It is used in conjunction with transformedBy.

    You must override one of {map, flatMap}. If you override both map and flatMap, flatMap takes precedence. If you fail to override one of {map, flatMap}, an AbstractMethodError will be thrown at Runtime.

    Note: to end a result with a failure, we encourage you to use either flatMap or rescue and return a failed Future, instead of throwing an exception. A failed future can be used by returning Future.exception(throwable) instead of throwing an exception.

    See also

    Future.transform which is the equivalent Scala API for further details.

    Future.transformedBy for using it with a Future.

    FutureEventListener for a Java API for side-effects.

  58. trait GZIPStringEncoder extends StringEncoder

    A collection of utilities for encoding strings and byte arrays to and decoding from strings compressed from with gzip.

    A collection of utilities for encoding strings and byte arrays to and decoding from strings compressed from with gzip.

    This trait is thread-safe because there are no streams shared outside of method scope, and therefore no contention for shared byte arrays.

    The encoding for strings is UTF-8.

    gzipping inherently includes base64 encoding (the GZIP utilities from java will complain otherwise!)

  59. class InterruptibleExecutorServiceFuturePool extends ExecutorServiceFuturePool

    A FuturePool backed by a java.util.concurrent.ExecutorService that supports cancellation.

  60. class JavaTimer extends Timer

    A Timer that is implemented via a java.util.Timer.

    A Timer that is implemented via a java.util.Timer.

    This timer has millisecond granularity.

    If your code has a reasonably high throughput of task scheduling and can trade off some precision of when tasks run, Finagle has a higher throughput hashed-wheel implementation.

    Note

    Due to the implementation using a single Thread, be wary of scheduling tasks that take a long time to execute (e.g. blocking IO) as this blocks other tasks from running at their scheduled time.

  61. class JsonThriftSerializer extends ThriftSerializer

    A thread-safe ThriftSerializer that uses TSimpleJSONProtocol.

  62. class LastWriteWinsQueue[A] extends Queue[A]

    An implementation of java.util.Queue that has LIFO order and a maximum capacity of 1 When the Queue is full, a push replaces the item.

  63. final class Local[T] extends AnyRef

    A Local is a ThreadLocal whose scope is flexible.

    A Local is a ThreadLocal whose scope is flexible. The state of all Locals may be saved or restored onto the current thread by the user. This is useful for threading Locals through execution contexts.

    Promises pass locals through control dependencies, not through data dependencies. This means that Locals have exactly the same semantics as ThreadLocals, if you think of continue (the asynchronous sequence operator) as semicolon (the synchronous sequence operator).

    Because it's not meaningful to inherit control from two places, Locals don't have to worry about having to merge two Contexts.

    Note: the implementation is optimized for situations in which save and restore optimizations are dominant.

  64. trait Managed[+T] extends AnyRef

    Managed[T] is a resource of type T which lifetime is explicitly managed.

    Managed[T] is a resource of type T which lifetime is explicitly managed. It is created with make(). Composite resources, which lifetimes are managed together, are created by the use of flatMap, ensuring proper construction and teardown of the comprised resources.

  65. class MockTimer extends Timer

    Exceedingly useful for writing well-behaved tests that need control over a Timer.

    Exceedingly useful for writing well-behaved tests that need control over a Timer. This is due to it playing well with the Time manipulation methods such as Time.withTimeAt, Time.withCurrentTimeFrozen, and so on.

    See also

    See the cookbook for examples.

  66. trait Monitor extends AnyRef

    A Monitor is a composable exception handler.

    A Monitor is a composable exception handler. It is independent of position, divorced from the notion of a call stack. Monitors do not recover values from failed computations: It handles only true exceptions that may require cleanup.

    See also

    AbstractMonitor for an API friendly to creating instances from Java.

  67. case class MonitorException(handlingExc: Throwable, monitorExc: Throwable) extends Exception with Product with Serializable

    Wraps an exception that happens when handling another exception in a monitor.

  68. final class Monitors extends AnyRef

    Java friendly APIs for the com.twitter.util.Monitor companion object.

  69. class NoFuture extends Future[Nothing]

    A Future which can never be satisfied and is thus always in the pending state.

    A Future which can never be satisfied and is thus always in the pending state.

    See also

    Future.never for an instance of it.

  70. class NullTimer extends Timer

    A NullTimer is not a timer at all: it invokes all tasks immediately and inline.

  71. trait Pool[A] extends AnyRef
  72. class Promise[A] extends Future[A] with Updatable[Try[A]]

    A writeable com.twitter.util.Future that supports merging.

    A writeable com.twitter.util.Future that supports merging. Callbacks (responders) of Promises are scheduled with com.twitter.concurrent.Scheduler.

    Implementation details

    A Promise is in one of six states: Waiting, Interruptible, Interrupted, Transforming, Done and Linked where Interruptible, Interrupted, and Transforming are variants of Waiting to deal with future interrupts. Promises are concurrency-safe, using lock-free operations throughout. Callback dispatch is scheduled with com.twitter.concurrent.Scheduler.

    Waiters (i.e., continuations) are stored in a Promise.WaitQueue and executed in the LIFO order.

    Promise.become merges two promises: they are declared equivalent. become merges the states of the two promises, and links one to the other. Thus promises support the analog to tail-call elimination: no space leak is incurred from flatMap in the tail position since intermediate promises are merged into the root promise.

  73. abstract class ProxyTimer extends Timer

    A Timer that proxies methods to self.

  74. class ReadWriteVar[T] extends UpdatableVar[T]

    Java adaptation of Var[T] with Updatable[T] with Extractable[T].

  75. trait ReferenceCountedTimer extends Timer
  76. class ReferenceCountingTimer extends ProxyTimer with ReferenceCountedTimer
  77. final case class Return[+R](r: R) extends Try[R] with Product with Serializable
  78. class ScheduledThreadPoolTimer extends Timer
  79. trait SignalHandler extends AnyRef
  80. class SimplePool[A] extends Pool[A]
  81. abstract class SlowProbeProxyTimer extends ProxyTimer

    An abstract ProxyTimer that provides callback methods which are called when a task takes longer than the specified maximum runtime or if a task is observed to be taking longer than the specified maximum runtime.

    An abstract ProxyTimer that provides callback methods which are called when a task takes longer than the specified maximum runtime or if a task is observed to be taking longer than the specified maximum runtime.

    Note

    Observation of slow task execution is performed when scheduling more work to avoid the overhead of another thread or timer checking on tasks. This results in lower overhead but means that slow running tasks may not be observed while executing. However, they will trigger a callback to the slowTaskCompleted regardless of whether additional work is scheduled.

    ,

    This makes assumptions that the underlying Timer will execute tasks sequentially in order to catch slow running tasks during execution. If the underlying Timer executes tasks in parallel the callback slowTaskExecuting will become unreliable. However, the slowTaskCompleted callback will remain reliable but must be a thread-safe implementation.

  82. trait StateMachine extends AnyRef
  83. trait Stopwatch extends AnyRef

    A stopwatch may be used to measure elapsed time.

  84. class StorageUnit extends Ordered[StorageUnit]

    Representation of storage units.

    Representation of storage units.

    Use either StorageUnit.fromX or com.twitter.conversions.storage implicit conversions from Long and Int to construct instances.

    import com.twitter.conversions.StorageUnitOps._
    import com.twitter.util.StorageUnit
    
    val size: StorageUnit = 10.kilobytes
    Note

    While all the methods in this abstraction are prefixed according to the International System of Units (kilo-, mega-, etc), they actually operate on the 1024 scale (not 1000).

    ,

    Operations can cause overflows of the Long used to represent the number of bytes.

  85. trait StringEncoder extends AnyRef
  86. class SunSignalHandler extends SignalHandler
  87. class ThreadStoppingTimer extends ProxyTimer
  88. class ThriftCodec[T <: TBase[_, _], P <: TProtocolFactory] extends Codec[T, Array[Byte]] with ThriftSerializer
  89. trait ThriftSerializer extends StringEncoder
  90. final case class Throw[+R](e: Throwable) extends Try[R] with Product with Serializable
  91. sealed class Time extends TimeLike[Time] with Serializable

    An absolute point in time, represented as the number of nanoseconds since the Unix epoch.

    An absolute point in time, represented as the number of nanoseconds since the Unix epoch.

    See also

    Duration for intervals between two points in time.

    Stopwatch for measuring elapsed time.

    TimeFormat for converting to and from String representations.

  92. trait TimeControl extends AnyRef
  93. class TimeFormat extends AnyRef

    A thread-safe wrapper around a SimpleDateFormat object.

    A thread-safe wrapper around a SimpleDateFormat object.

    The default timezone is UTC.

  94. trait TimeLike[This <: TimeLike[This]] extends Ordered[This]

    A common trait for time-like values.

    A common trait for time-like values. It requires a companion TimeLikeOps module. TimeLikes are finite, but they must always have two sentinels: Top and Bottom. These act like positive and negative infinities: Arithmetic involving them preserves their values, and so on.

    TimeLikes are Long-valued nanoseconds, but have different interpretations: Durations measure the number of nanoseconds between two points in time, while Time measure the number of nanoseconds since the Unix epoch (1 January 1970 00:00:00 UTC).

    TimeLike behave like boxed java Double values with respect to infinity and undefined values. In particular, this means that a TimeLike's Undefined value is comparable to other values. In turn this means it can be used as keys in maps, etc.

    Overflows are also handled like doubles.

  95. trait TimeLikeOps[This <: TimeLike[This]] extends AnyRef

  96. class TimeoutException extends java.util.concurrent.TimeoutException
  97. trait Timer extends AnyRef

    Timers are used to schedule tasks in the future.

    Timers are used to schedule tasks in the future. They support both one-shot and recurring tasks.

    Timers propagate Local state, including the Monitor, from when the task is scheduled to when it is run.

    Note

    Scheduling tasks with Timers should rarely be done directly; for example, when programming with Futures, prefer using Future.sleep.

    See also

    MockTimer for use in tests that require determinism.

  98. trait TimerTask extends Closable

    TimerTasks represent pending tasks scheduled by a Timer.

  99. abstract class TokenBucket extends AnyRef

    A token bucket is used to control the relative rates of two processes: one fills the bucket, another empties it.

  100. sealed abstract class Try[+R] extends AnyRef

    This class represents a computation that can succeed or fail.

    This class represents a computation that can succeed or fail. It has two concrete implementations, Return (for success) and Throw (for failure)

  101. trait Updatable[-T] extends AnyRef

    Denotes an updatable container.

  102. trait Var[+T] extends AnyRef

    Vars are values that vary over time.

    Vars are values that vary over time. To create one, you must give it an initial value.

    val a = Var[Int](1)

    A Var created this way can be sampled to retrieve its current value,

    println(Var.sample(a)) // prints 1

    or, invoked to assign it new values.

    a.update(2)
    println(Var.sample(a)) // prints 2

    Vars can be derived from other Vars.

    val b = a.flatMap { x => Var(x + 2) }
    println(Var.sample(b)) // prints 4

    And, if the underlying is assigned a new value, the derived Var is updated. Updates are computed lazily, so while assignment is cheap, sampling is where we pay the cost of the computation required to derive the new Var.

    a.update(1)
    println(Var.sample(b)) // prints 3

    A key difference between the derived Var and its underlying is that derived Vars can't be assigned new values. That's why b, from the example above, can't be invoked to assign it a new value, it can only be sampled.

    Note

    Vars do not always perform the minimum amount of re-computation.

    ,

    There are no well-defined error semantics for Var. Vars are computed lazily, and the updating thread will receive any exceptions thrown while computing derived Vars. Note: There is a Java-friendly API for this trait: com.twitter.util.AbstractVar.

  103. final class Vars extends AnyRef

    A Java adaptation of com.twitter.util.Var companion object.

  104. trait Witness[-N] extends AnyRef

    A witness is the recipient of Event.

    A witness is the recipient of Event.

    Note: There is a Java-friendly API for this trait: com.twitter.util.AbstractWitness.

  105. class WitnessedEvent[T] extends Event[T] with Witness[T]

    A Java analog of Event[A]().

  106. final class Witnesses extends AnyRef

    A Java adaptation of com.twitter.util.Witness companion object.

  107. trait WrappedValue[T] extends Any

    WrappedValue is a marker interface intended for use by case classes wrapping a single value.

    WrappedValue is a marker interface intended for use by case classes wrapping a single value. The intent is to signal that the underlying value should be directly serialized or deserialized ignoring the wrapping case class.

    WrappedValue is a Universal Trait so that it can be used by value classes.

    Usage

    case class WrapperA(underlying: Int) extends WrappedValue[Int]
    case class WrapperB(underlying: Int) extends AnyVal with WrappedValue[Int]

Value Members

  1. object Activity extends Serializable

    Note: There is a Java-friendly API for this object: com.twitter.util.Activities.

  2. object Await

    Synchronously await the result of some action by blocking the current thread.

    Synchronously await the result of some action by blocking the current thread.

    The two main uses of Await are (a) you have synchronous code that needs to wait on some action performed by asynchronous code, or (b) you have synchronous code that needs to wait on some action performed on a thread pool or otherwise a different thread.

    A common type of Awaitable is the com.twitter.util.Future.

    In the context of an event loop (such as when you are on a Finagle thread), never synchronously wait for completion - favoring asynchronous methods such as combinators or callbacks registered on a Future.

  3. object Awaitable
  4. object Base64Long

    Efficient conversion between Longs and base 64 encoded strings.

    Efficient conversion between Longs and base 64 encoded strings.

    This is intended for use in e.g. cache keys.

  5. object Base64StringEncoder extends Base64StringEncoder
  6. object Base64UrlSafeStringEncoder extends Base64UrlSafeStringEncoder
  7. object BinaryCodec
  8. object Cancellable
  9. object Closable

    Note: There is a Java-friendly API for this object: com.twitter.util.Closables.

  10. object ClosableOnce
  11. object Codec extends EncoderCompanion with DecoderCompanion
  12. object Decoder extends DecoderCompanion
  13. object Diffable

    Diffable defines common type class instances for Diffable.

  14. object Disposable
  15. object Duration extends TimeLikeOps[Duration] with Serializable
  16. object Encoder extends EncoderCompanion
  17. object Event

    Note: There is a Java-friendly API for this object: com.twitter.util.Events.

  18. object Function
  19. object Future

    See also

    Futures for Java-friendly APIs.

    The user guide on concurrent programming with Futures.

  20. object FuturePool

    Note: There is a Java-friendly API for this object: com.twitter.util.FuturePools.

  21. object FutureTask
  22. object Futures

    Twitter Future utility methods for ease of use from java

  23. object GZIPStringEncoder extends GZIPStringEncoder
  24. object HandleSignal
  25. object Local
  26. object Managed
  27. object Memoize
  28. object Monitor extends Monitor

    Defines the (Future)-Local monitor as well as some monitor utilities.

    Defines the (Future)-Local monitor as well as some monitor utilities.

    Java users should use the Monitors class.

  29. object NetUtil
  30. object NilStopwatch extends Stopwatch

    A trivial implementation of Stopwatch for use as a null object.

    A trivial implementation of Stopwatch for use as a null object.

    All calls to Stopwatch.start return an Stopwatch.Elapsed instance that always returns Duration.Bottom for its elapsed time.

    See also

    NilStopwatch.get for accessing this instance from Java.

  31. object NullMonitor extends Monitor

    A monitor that always fails to handle an exception.

    A monitor that always fails to handle an exception. Combining this with any other Monitor will simply return the other Monitor effectively removing NullMonitor from the chain.

  32. object NullTimerTask extends TimerTask
  33. object Promise

  34. object RandomSocket

    A generator of random local java.net.InetSocketAddress objects with ephemeral ports.

  35. object Return extends Serializable
  36. object RootMonitor extends Monitor
  37. object SignalHandlerFactory
  38. object StateMachine
  39. object Stopwatch extends Stopwatch

    The system Stopwatch measures elapsed time using System.nanoTime.

    The system Stopwatch measures elapsed time using System.nanoTime.

    Note that it works well with unit tests by respecting time manipulation on Time.

    See also

    Stopwatches for Java APIs.

  40. object Stopwatches

    Java APIs for Stopwatch.

  41. object StorageUnit
  42. object StringEncoder extends StringEncoder
  43. object SunSignalHandler
  44. object ThriftCodec
  45. object Throw extends Serializable
  46. object Throwables
  47. object Time extends TimeLikeOps[Time] with Serializable

    By using Time.now in your program instead of System.currentTimeMillis unit tests are able to adjust the current time to verify timeouts and other time-dependent behavior, without calling sleep, and providing deterministic tests.

    By using Time.now in your program instead of System.currentTimeMillis unit tests are able to adjust the current time to verify timeouts and other time-dependent behavior, without calling sleep, and providing deterministic tests.

    The current time can be manipulated via Time.withTimeAt, Time.withCurrentTimeFrozen, Time.withTimeFunction and Time.sleep.

    While now is not a "global" it is however properly propagated through to other code via the standard usage of Locals throughout util. Specifically, code using Futures, FuturePools, and MockTimers will have their code see the manipulated values.

    val time = Time.fromMilliseconds(123456L)
    Time.withTimeAt(time) { timeControl =>
      assert(Time.now == time)
    
      // you can control time via the `TimeControl` instance.
      timeControl.advance(2.seconds)
      FuturePool.unboundedPool {
        assert(Time.now == time + 2.seconds)
      }
    }
    See also

    Duration for intervals between two points in time.

    Stopwatch for measuring elapsed time.

    TimeFormat for converting to and from String representations.

  48. object Timer
  49. object TokenBucket
  50. object Try

    The Try type represents a computation that may either result in an exception or return a success value.

    The Try type represents a computation that may either result in an exception or return a success value. It is analogous to the Either type but encodes common idioms for handling exceptional cases (such as rescue/ensure which is analogous to try/finally).

  51. object TwitterDateFormat

    A java.text.SimpleDateFormat that avoids confusion between YYYY and yyyy.

    A java.text.SimpleDateFormat that avoids confusion between YYYY and yyyy. One should never use YYYY (week year) unless the format also includes the week of year.

  52. object Unsafe
  53. object Updatable
  54. object Var

    Note: There is a Java-friendly API for this object: com.twitter.util.Vars.

  55. object Witness

    Note: There is Java-friendly API for this object: com.twitter.util.Witnesses.

Ungrouped