com.twitter

util

package util

Linear Supertypes
AnyRef, Any
Ordering
  1. Alphabetic
  2. By inheritance
Inherited
  1. util
  2. AnyRef
  3. Any
  1. Hide All
  2. Show all
Learn more about member selection
Visibility
  1. Public
  2. All

Type Members

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

    An Activity is a handle to a concurrently running process, producing T-typed values.

    An Activity is a handle to a concurrently running process, producing T-typed values. An activity is 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.

    (The observant reader will notice that this is really a monad transformer for an Op monad over Var where Op is like a Try with an additional pending state.)

  2. 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.

  3. class BoundedStack[A] extends Seq[A]

    A "stack" with a bounded size.

    A "stack" with a bounded size. If you push a new element on the top when the stack is full, the oldest element gets dropped off the bottom.

  4. 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.

  5. class CancellableSink extends Cancellable

  6. trait Closable extends AnyRef

    Closable is a mixin trait to describe a closable resource.

  7. trait CloseAwaitably extends Awaitable[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
    }
    }
  8. trait Codec[T, S] extends Bijection[T, S] with Encoder[T, S] with Decoder[T, S]

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

  9. abstract class Command[-T1] extends (T1) ⇒ Unit

  10. 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.

  11. class CountDownLatch extends AnyRef

  12. class Credentials extends AnyRef

    Java interface to Credentials.

  13. trait Decoder[T, S] extends AnyRef

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

  14. trait DecoderCompanion extends AnyRef

  15. 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.

  16. class DoubleTrouble extends Exception

  17. 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.time._
    
    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.

  18. trait Encoder[T, S] extends (T) ⇒ S

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

  19. trait EncoderCompanion extends AnyRef

  20. trait Event[+T] extends AnyRef

    Events are instantaneous values, defined only at particular instants in time (cf.

    Events are instantaneous values, defined only at particular instants in time (cf. Vars, which are defined at all times). It is possible to view Events as the discrete counterpart to Var's continuous nature.

    Events are observed by registering com.twitter.util.Witness Witnesss to which the Event's values are notified.

  21. abstract class ExceptionalFunction[-T1, +R] extends Function[T1, R]

  22. abstract class ExceptionalFunction0[+R] extends Function0[R]

  23. class ExecutorServiceFuturePool extends FuturePool

    A FuturePool implementation backed by an ExecutorService.

    A FuturePool implementation backed by an 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

  24. trait Extractable[T] extends AnyRef

  25. abstract class FactoryPool[A] extends Pool[A]

  26. 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.

  27. abstract class Function0[+R] extends () ⇒ R

  28. abstract class Function2[-T1, -T2, +R] extends (T1, T2) ⇒ R

  29. abstract class Future[+A] extends Awaitable[A]

    A computation evaluated asynchronously.

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

    Futures are also com.twitter.util.Cancellable, but with special semantics: the cancellation signal is only guaranteed to be delivered when the promise has not yet completed.

  30. class FutureCancelledException extends Exception

  31. trait FutureEventListener[T] extends AnyRef

    An alternative interface for handling Future Events.

    An alternative interface for handling Future Events. This interface is designed to be friendly to Java users since it does not require creating many small Function objects.

  32. class FutureNonLocalReturnControl extends Exception

  33. trait FuturePool extends AnyRef

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

  34. class FutureTask[A] extends Promise[A] with Runnable

  35. 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: an exception e thrown in any of map/flatMap/handle/rescue will make the result of transformedBy be equivalent to Future.exception(e).

  36. class InterruptibleExecutorServiceFuturePool extends ExecutorServiceFuturePool

  37. trait JavaSingleton extends AnyRef

    A mixin to allow scala objects to be used from java.

  38. class JavaTimer extends Timer

  39. 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.

  40. 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 com.twitter.util.Local$.Contexts.

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

  41. class LongOverflowException extends Exception

  42. 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.

  43. class MockTimer extends Timer

  44. 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 a failed computations: It handles only true exceptions that may require cleanup.

  45. 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.

  46. class NoFuture extends Future[Nothing]

    A future with no future (never completes).

  47. trait NoStacktrace extends Exception

  48. class NullTimer extends Timer

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

  49. trait Pool[A] extends AnyRef

  50. class Promise[A] extends Future[A] with Responder[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 five states: Waiting, Interruptible, Interrupted, Done and Linked where Interruptible and Interrupted 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 are stored as a com.twitter.util.Promise.K. Ks (mnemonic: continuation) specifies a depth. This is used to implement Promise chaining: a callback with depth d is invoked only after all callbacks with depth < d have already been invoked.

    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.

    A number of optimizations are employed to conserve space: we pay particular heed to the JVM's object representation, in particular for OpenJDK (HotSpot) version 7 running on 64-bit architectures with compressed OOPS. See comments on com.twitter.util.Promise.State for details.

  51. trait ReferenceCountedTimer extends Timer

  52. class ReferenceCountingTimer extends ReferenceCountedTimer

  53. final case class Return[+R](r: R) extends Try[R] with Product with Serializable

  54. class RichU64ByteArray extends AnyRef

  55. class RichU64Long extends AnyRef

  56. class RichU64String extends AnyRef

    RichU64String parses string as a 64-bit unsigned hexadecimal long, outputting a signed Long or a byte array.

    RichU64String parses string as a 64-bit unsigned hexadecimal long, outputting a signed Long or a byte array. Valid input is 1-16 hexadecimal digits (0-9, a-z, A-Z).

    Exceptions thrown
    NumberFormatException

    if string is not a non-negative hexadecimal string

  57. class RingBuffer[A] extends Seq[A]

  58. class ScheduledThreadPoolTimer extends Timer

  59. trait SignalHandler extends AnyRef

  60. class SimplePool[A] extends Pool[A]

  61. trait StateMachine extends AnyRef

  62. trait Stopwatch extends AnyRef

    A stopwatch may be used to measure elapsed time.

  63. class StorageUnit extends Ordered[StorageUnit]

    Representation of storage units.

    Representation of storage units.

    If you import the com.twitter.conversions.storage implicits you can write human-readable values such as 1.gigabyte or 50.megabytes.

  64. class SunSignalHandler extends SignalHandler

  65. trait TempFolder extends AnyRef

    Test mixin that creates a new folder for a block of code to execute in.

    Test mixin that creates a new folder for a block of code to execute in. The folder is recursively deleted after the test.

    Note, the com.twitter.util.io package would be a better home for this trait.

  66. class ThreadStoppingTimer extends Timer

  67. final case class Throw[+R](e: Throwable) extends Try[R] with Product with Serializable

  68. sealed class Time extends TimeLike[Time] with Serializable

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

  69. trait TimeControl extends AnyRef

  70. class TimeFormat extends AnyRef

    A thread-safe wrapper around a SimpleDateFormat object.

    A thread-safe wrapper around a SimpleDateFormat object.

    The timezone used will be UTC.

  71. 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.

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

  73. class TimeoutException extends java.util.concurrent.TimeoutException

  74. trait Timer extends AnyRef

  75. trait TimerTask extends Closable

  76. 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)

  77. trait Updatable[T] extends AnyRef

    Denotes an updatable container.

  78. trait Var[+T] extends AnyRef

    Trait Var represents a variable.

    Trait Var represents a variable. It is a reference cell which is composable: dependent Vars (derived through flatMap) are recomputed automatically when independent variables change -- they implement a form of self-adjusting computation.

    Vars are observed, notifying users whenever the variable changes.

    Note

    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.

    ,

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

  79. trait Witness[-N] extends AnyRef

    A witness is the recipient of Event.

  80. trait Bijection[A, B] extends (A) ⇒ B

    A bijection is a function for which every value in its codomain (set of all possible results) is equivalent to application of the function on a unique value in its domain (all possible inputs).

    A bijection is a function for which every value in its codomain (set of all possible results) is equivalent to application of the function on a unique value in its domain (all possible inputs). This trait in particular provides an interface for functions that can be 'unapplied' as well as applied. A codec that can convert to and from a set of objects and their serialized form is an example of a bijection.

    Annotations
    @deprecated
    Deprecated

    (Since version 2014-06-05) Prefer using com.twitter.bijection.Bijection

  81. trait Config[T] extends () ⇒ T

    A config object contains vars for configuring an object of type T, and an apply() method which turns this config into an object of type T.

    A config object contains vars for configuring an object of type T, and an apply() method which turns this config into an object of type T.

    The trait also contains a few useful implicits.

    You can define fields that are required but that don't have a default value with: class BotConfig extends Config[Bot] { var botName = required[String] var botPort = required[Int] .... }

    Optional fields can be defined with: var something = optional[Duration]

    Fields that are dependent on other fields and have a default value computed from an expression should be marked as computed:

    var level = required[Int] var nextLevel = computed { level + 1 }

    Annotations
    @deprecated
    Deprecated

    (Since version ) use a Plain Old Scala Object

Value Members

  1. object Activity extends Serializable

  2. object Await

    Await the result of some action.

  3. object Awaitable

  4. object Base64Long

    Efficient conversion of Longs to base 64 encoded strings.

    Efficient conversion of Longs to base 64 encoded strings.

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

  5. object BinaryCodec

  6. object Cancellable

  7. object Closable

  8. object Codec extends EncoderCompanion with DecoderCompanion

  9. object Credentials

    Simple helper to read authentication credentials from a text file.

    Simple helper to read authentication credentials from a text file.

    The file's format is assumed to be trivialized yaml, containing lines of the form key: value.

  10. object Decoder extends DecoderCompanion

  11. object Disposable

  12. object Duration extends TimeLikeOps[Duration] with Serializable

  13. object Encoder extends EncoderCompanion

  14. object Event

  15. object Function

  16. object Future

  17. object FuturePool

  18. object FutureTask

  19. object HandleSignal

  20. object Local

  21. object LongOverflowArith

  22. object Managed

  23. object Memoize

  24. object Monitor extends Monitor

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

  25. object NetUtil

  26. object NilStopwatch extends Stopwatch

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

  27. object NoStacktrace extends Serializable

  28. object NonFatal

    A classifier of fatal exceptions

  29. 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.

  30. object NullTimerTask extends TimerTask

  31. object Promise

  32. object RandomSocket

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

  33. object Return extends Serializable

  34. object RootMonitor extends Monitor

  35. object SignalHandlerFactory

  36. object StateMachine

  37. object Stopwatch extends Stopwatch

    The system com.twitter.util.Stopwatch measures elapsed time using System.nanoTime.

  38. object StorageUnit

  39. val StorageUnitConversions: storage.type

  40. object SunSignalHandler

  41. object Time extends TimeLikeOps[Time] with Serializable

    Use Time.now in your program instead of System.currentTimeMillis, and unit tests will be able to adjust the current time to verify timeouts and other time-dependent behavior, without calling sleep.

    Use Time.now in your program instead of System.currentTimeMillis, and unit tests will be able to adjust the current time to verify timeouts and other time-dependent behavior, without calling sleep.

    If you import the com.twitter.conversions.time implicits you can write human-readable values such as 1.minute or 250.millis.

  42. val TimeConversions: time.type

  43. object Timer

  44. 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).

  45. object U64

  46. object Unsafe

  47. object Var

  48. object Witness

  49. package repository

Deprecated Value Members

  1. object Bijection

    Annotations
    @deprecated
    Deprecated

    (Since version 6.17.1) Prefer using com.twitter.bijection.Bijection

  2. object Config

    You can import Config._ if you want the auto-conversions in a class that does not inherit from trait Config.

    You can import Config._ if you want the auto-conversions in a class that does not inherit from trait Config.

    Annotations
    @deprecated
    Deprecated

    (Since version ) use a Plain Old Scala Object

Inherited from AnyRef

Inherited from Any

Ungrouped