package concurrent
This package object contains primitives for concurrent and parallel programming.
Guide
A more detailed guide to Futures and Promises, including discussion and examples can be found at https://docs.scala-lang.org/overviews/core/futures.html.
Common Imports
When working with Futures, you will often find that importing the whole concurrent package is convenient:
import scala.concurrent._When using things like Futures, it is often required to have an implicit ExecutionContext
in scope. The general advice for these implicits are as follows.
If the code in question is a class or method definition, and no ExecutionContext is available,
request one from the caller by adding an implicit parameter list:
def myMethod(myParam: MyType)(implicit ec: ExecutionContext) = … //Or class MyClass(myParam: MyType)(implicit ec: ExecutionContext) { … }
This allows the caller of the method, or creator of the instance of the class, to decide which
ExecutionContext should be used.
For typical REPL usage and experimentation, importing the global ExecutionContext is often desired.
import scala.concurrent.ExcutionContext.Implicits.globalSpecifying Durations
Operations often require a duration to be specified. A duration DSL is available to make defining these easier:
import scala.concurrent.duration._ val d: Duration = 10.seconds
Using Futures For Non-blocking Computation
Basic use of futures is easy with the factory method on Future, which executes a provided function asynchronously, handing you back a future result of that function without blocking the current thread. In order to create the Future you will need either an implicit or explicit ExecutionContext to be provided:
import scala.concurrent._ import ExecutionContext.Implicits.global // implicit execution context val firstZebra: Future[Int] = Future { val words = Files.readAllLines("/etc/dictionaries-common/words").asScala words.indexOfSlice("zebra") }
Avoid Blocking
Although blocking is possible in order to await results (with a mandatory timeout duration):
import scala.concurrent.duration._ Await.result(firstZebra, 10.seconds)
and although this is sometimes necessary to do, in particular for testing purposes, blocking in general is discouraged when working with Futures and concurrency in order to avoid potential deadlocks and improve performance. Instead, use callbacks or combinators to remain in the future domain:
val animalRange: Future[Int] = for { aardvark <- firstAardvark zebra <- firstZebra } yield zebra - aardvark animalRange.onSuccess { case x if x > 500000 => println("It's a long way from Aardvark to Zebra") }
- Source
- package.scala
- Alphabetic
- By Inheritance
- concurrent
- AnyRef
- Any
- Hide All
- Show All
- Public
- Protected
Type Members
- trait Awaitable[+T] extends AnyRef
An object that may eventually be completed with a result value of type
Twhich may be awaited using blocking methods.An object that may eventually be completed with a result value of type
Twhich may be awaited using blocking methods.The Await object provides methods that allow accessing the result of an
Awaitableby blocking the current thread until theAwaitablehas been completed or a timeout has occurred. - trait Batchable extends AnyRef
Marker trait to indicate that a Runnable is Batchable by BatchingExecutors
- trait BlockContext extends AnyRef
A context to be notified by scala.concurrent.blocking when a thread is about to block.
A context to be notified by scala.concurrent.blocking when a thread is about to block. In effect this trait provides the implementation for scala.concurrent.Await. scala.concurrent.Await.result and scala.concurrent.Await.ready locates an instance of
BlockContextby first looking for one provided through BlockContext.withBlockContext and failing that, checking whetherThread.currentThreadis an instance ofBlockContext. So a thread pool can have itsjava.lang.Threadinstances implementBlockContext. There's a defaultBlockContextused if the thread doesn't implementBlockContext.Typically, you'll want to chain to the previous
BlockContext, like this:val oldContext = BlockContext.current val myContext = new BlockContext { override def blockOn[T](thunk: => T)(implicit permission: CanAwait): T = { // you'd have code here doing whatever you need to do // when the thread is about to block. // Then you'd chain to the previous context: oldContext.blockOn(thunk) } } BlockContext.withBlockContext(myContext) { // then this block runs with myContext as the handler // for scala.concurrent.blocking }
- sealed trait CanAwait extends AnyRef
This marker trait is used by Await to ensure that Awaitable.ready and Awaitable.result are not directly called by user code.
This marker trait is used by Await to ensure that Awaitable.ready and Awaitable.result are not directly called by user code. An implicit instance of this trait is only available when user code is currently calling the methods on Await.
- Annotations
- @implicitNotFound()
- type CancellationException = java.util.concurrent.CancellationException
- trait ExecutionContext extends AnyRef
An
ExecutionContextcan execute program logic asynchronously, typically but not necessarily on a thread pool.An
ExecutionContextcan execute program logic asynchronously, typically but not necessarily on a thread pool.A general purpose
ExecutionContextmust be asynchronous in executing anyRunnablethat is passed into itsexecute-method. A special purposeExecutionContextmay be synchronous but must only be passed to code that is explicitly safe to be run using a synchronously executingExecutionContext.APIs such as
Future.onCompleterequire you to provide a callback and an implicitExecutionContext. The implicitExecutionContextwill be used to execute the callback.While it is possible to simply import
scala.concurrent.ExecutionContext.Implicits.globalto obtain an implicitExecutionContext, application developers should carefully consider where they want to define the execution policy; ideally, one place per application — or per logically related section of code — will make a decision about whichExecutionContextto use. That is, you will mostly want to avoid hardcoding, especially via an import,scala.concurrent.ExecutionContext.Implicits.global. The recommended approach is to add(implicit ec: ExecutionContext)to methods, or class constructor parameters, which need anExecutionContext.Then locally import a specific
ExecutionContextin one place for the entire application or module, passing it implicitly to individual methods. Alternatively define a local implicit val with the requiredExecutionContext.A custom
ExecutionContextmay be appropriate to execute code which blocks on IO or performs long-running computations.ExecutionContext.fromExecutorServiceandExecutionContext.fromExecutorare good ways to create a customExecutionContext.The intent of
ExecutionContextis to lexically scope code execution. That is, each method, class, file, package, or application determines how to run its own code. This avoids issues such as running application callbacks on a thread pool belonging to a networking library. The size of a networking library's thread pool can be safely configured, knowing that only that library's network operations will be affected. Application callback execution can be configured separately.- Annotations
- @implicitNotFound()
- trait ExecutionContextExecutor extends ExecutionContext with Executor
An ExecutionContext that is also a Java Executor.
- trait ExecutionContextExecutorService extends ExecutionContextExecutor with ExecutorService
An ExecutionContext that is also a Java ExecutorService.
- type ExecutionException = java.util.concurrent.ExecutionException
- trait Future[+T] extends Awaitable[T]
A
Futurerepresents a value which may or may not *currently* be available, but will be available at some point, or an exception if that value could not be made available.A
Futurerepresents a value which may or may not *currently* be available, but will be available at some point, or an exception if that value could not be made available.Asynchronous computations that yield futures are created with the
Future.applycall and are computed using a suppliedExecutionContext, which can be backed by a Thread pool.import ExecutionContext.Implicits.global val s = "Hello" val f: Future[String] = Future { s + " future!" } f foreach { msg => println(msg) }
- See also
- trait Promise[T] extends AnyRef
Promise is an object which can be completed with a value or failed with an exception.
Promise is an object which can be completed with a value or failed with an exception.
A promise should always eventually be completed, whether for success or failure, in order to avoid unintended resource retention for any associated Futures' callbacks or transformations.
- type TimeoutException = java.util.concurrent.TimeoutException
Deprecated Type Members
- class Channel[A] extends AnyRef
This class provides a simple FIFO queue of data objects, which are read by one or more reader threads.
This class provides a simple FIFO queue of data objects, which are read by one or more reader threads.
- A
type of data exchanged
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Use
java.util.concurrent.LinkedTransferQueueinstead.
- class DelayedLazyVal[T] extends AnyRef
A
DelayedLazyValis a wrapper for lengthy computations which have a valid partially computed result.A
DelayedLazyValis a wrapper for lengthy computations which have a valid partially computed result.The first argument is a function for obtaining the result at any given point in time, and the second is the lengthy computation. Once the computation is complete, the
applymethod will stop recalculating it and return a fixed value from that point forward.- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0)
DelayedLazyValWill be removed in the future.
- trait OnCompleteRunnable extends Batchable
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Superseded by
scala.concurrent.Batchable
- class SyncChannel[A] extends AnyRef
A
SyncChannelallows one to exchange data synchronously between a reader and a writer thread.A
SyncChannelallows one to exchange data synchronously between a reader and a writer thread. The writer thread is blocked until the data to be written has been read by a corresponding reader thread.- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Use
java.util.concurrent.Exchangerinstead.
- class SyncVar[A] extends AnyRef
A class to provide safe concurrent access to a mutable cell.
A class to provide safe concurrent access to a mutable cell. All methods are synchronized.
- A
type of the contained value
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Use
java.util.concurrent.LinkedBlockingQueue with capacity 1instead.
Value Members
- final def blocking[T](body: => T): T
Used to designate a piece of code which potentially blocks, allowing the current BlockContext to adjust the runtime's behavior.
Used to designate a piece of code which potentially blocks, allowing the current BlockContext to adjust the runtime's behavior. Properly marking blocking code may improve performance or avoid deadlocks.
Blocking on an Awaitable should be done using Await.result instead of
blocking.- body
A piece of code which contains potentially blocking or long running calls.
- Annotations
- @throws(clazz = classOf[Exception])
- Exceptions thrown
CancellationExceptionif the computation was cancelledInterruptedExceptionin the case that a wait within the blockingbodywas interrupted
- object Await
Awaitis what is used to ensure proper handling of blocking forAwaitableinstances.Awaitis what is used to ensure proper handling of blocking forAwaitableinstances.While occasionally useful, e.g. for testing, it is recommended that you avoid Await whenever possible— instead favoring combinators and/or callbacks. Await's
resultandreadymethods will block the calling thread's execution until they return, which will cause performance degradation, and possibly, deadlock issues. - object BlockContext
- object ExecutionContext
Contains factory methods for creating execution contexts.
- object Future
Future companion object.
- object Promise
Deprecated Value Members
- object JavaConversions
The
JavaConversionsobject provides implicit conversions supporting interoperability between Scala and Java concurrency classes.The
JavaConversionsobject provides implicit conversions supporting interoperability between Scala and Java concurrency classes.- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Use the factory methods in
ExecutionContextinstead
This is the documentation for the Scala standard library.
Package structure
The scala package contains core types like
Int,Float,ArrayorOptionwhich are accessible in all Scala compilation units without explicit qualification or imports.Notable packages include:
scala.collectionand its sub-packages contain Scala's collections frameworkscala.collection.immutable- Immutable, sequential data-structures such asVector,List,Range,HashMaporHashSetscala.collection.mutable- Mutable, sequential data-structures such asArrayBuffer,StringBuilder,HashMaporHashSetscala.collection.concurrent- Mutable, concurrent data-structures such asTrieMapscala.concurrent- Primitives for concurrent programming such asFuturesandPromisesscala.io- Input and output operationsscala.math- Basic math functions and additional numeric types likeBigIntandBigDecimalscala.sys- Interaction with other processes and the operating systemscala.util.matching- Regular expressionsOther packages exist. See the complete list on the right.
Additional parts of the standard library are shipped as separate libraries. These include:
scala.reflect- Scala's reflection API (scala-reflect.jar)scala.xml- XML parsing, manipulation, and serialization (scala-xml.jar)scala.collection.parallel- Parallel collections (scala-parallel-collections.jar)scala.util.parsing- Parser combinators (scala-parser-combinators.jar)scala.swing- A convenient wrapper around Java's GUI framework called Swing (scala-swing.jar)Automatic imports
Identifiers in the scala package and the
scala.Predefobject are always in scope by default.Some of these identifiers are type aliases provided as shortcuts to commonly used classes. For example,
Listis an alias forscala.collection.immutable.List.Other aliases refer to classes provided by the underlying platform. For example, on the JVM,
Stringis an alias forjava.lang.String.