Movatterモバイル変換


[0]ホーム

URL:


Scala 3
3.7.4
LearnInstallPlaygroundFind A LibraryCommunityBlog
Scala 3
LearnInstallPlaygroundFind A LibraryCommunityBlog
DocsAPI
Generated with
Copyright (c) 2002-2025, LAMP/EPFL
Copyright (c) 2002-2025, LAMP/EPFL
Scala 3/scala/scala.concurrent

scala.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 athttps://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 likeFutures, it is often required to have an implicitExecutionContext in scope. The general advice for these implicits are as follows.

If the code in question is a class or method definition, and noExecutionContext is available, request one from the caller by adding an implicit parameter list:

def myMethod(myParam: MyType)(implicit ec: ExecutionContext) = …//Orclass MyClass(myParam: MyType)(implicit ec: ExecutionContext) { … }

This allows the caller of the method, or creator of the instance of the class, to decide whichExecutionContext should be used.

For typical REPL usage and experimentation, importing the globalExecutionContext is often desired.

import scala.concurrent.ExcutionContext.Implicits.global

Specifying 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 contextval 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 - aardvarkanimalRange.onSuccess { case x if x > 500000 => println("It's a long way from Aardvark to Zebra")}

Attributes

Members list

Type members

Classlikes

objectAwait

Await is what is used to ensure proper handling of blocking forAwaitable instances.

Await is what is used to ensure proper handling of blocking forAwaitable instances.

While occasionally useful, e.g. for testing, it is recommended that you avoid Await whenever possible— instead favoring combinators and/or callbacks. Await'sresult andready methods will block the calling thread's execution until they return, which will cause performance degradation, and possibly, deadlock issues.

Attributes

Source
package.scala
Supertypes
classObject
traitMatchable
classAny
Self type
Await.type
traitAwaitable[+T]

An object that may eventually be completed with a result value of typeT which may be awaited using blocking methods.

An object that may eventually be completed with a result value of typeT which may be awaited using blocking methods.

TheAwait object provides methods that allow accessing the result of anAwaitable by blocking the current thread until theAwaitable has been completed or a timeout has occurred.

Attributes

Source
Awaitable.scala
Supertypes
classObject
traitMatchable
classAny
Known subtypes
traitFuture[T]
objectnever

Marker trait to indicate that a Runnable is Batchable by BatchingExecutors

Marker trait to indicate that a Runnable is Batchable by BatchingExecutors

Attributes

Source
BatchingExecutor.scala
Supertypes
classObject
traitMatchable
classAny
Known subtypes
Self type

A context to be notified byscala.concurrent.blocking when a thread is about to block.

A context to be notified byscala.concurrent.blocking when a thread is about to block. In effect this trait provides the implementation forscala.concurrent.Await.scala.concurrent.Await.result andscala.concurrent.Await.ready locates an instance ofBlockContext by first looking for one provided throughBlockContext.withBlockContext and failing that, checking whetherThread.currentThread is an instance ofBlockContext. So a thread pool can have itsjava.lang.Thread instances implementBlockContext. There's a defaultBlockContext used if the thread doesn't implementBlockContext.

Typically, you'll want to chain to the previousBlockContext, like this:

val oldContext = BlockContext.currentval 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}

Attributes

Companion
object
Source
BlockContext.scala
Supertypes
classObject
traitMatchable
classAny

Attributes

Companion
trait
Source
BlockContext.scala
Supertypes
classObject
traitMatchable
classAny
Self type
sealedtraitCanAwait

This marker trait is used byAwait to ensure thatAwaitable.ready andAwaitable.result are not directly called by user code.

This marker trait is used byAwait to ensure thatAwaitable.ready andAwaitable.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 onAwait.

Attributes

Source
package.scala
Supertypes
classObject
traitMatchable
classAny

AnExecutionContext can execute program logic asynchronously, typically but not necessarily on a thread pool.

AnExecutionContext can execute program logic asynchronously, typically but not necessarily on a thread pool.

A general purposeExecutionContext must be asynchronous in executing anyRunnable that is passed into itsexecute-method. A special purposeExecutionContext may be synchronous but must only be passed to code that is explicitly safe to be run using a synchronously executingExecutionContext.

APIs such asFuture.onComplete require you to provide a callback and an implicitExecutionContext. The implicitExecutionContext will be used to execute the callback.

While it is possible to simply importscala.concurrent.ExecutionContext.Implicits.global to 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 whichExecutionContext to 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 specificExecutionContext in one place for the entire application or module, passing it implicitly to individual methods. Alternatively define a local implicit val with the requiredExecutionContext.

A customExecutionContext may be appropriate to execute code which blocks on IO or performs long-running computations.ExecutionContext.fromExecutorService andExecutionContext.fromExecutor are good ways to create a customExecutionContext.

The intent ofExecutionContext is 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.

Attributes

Companion
object
Source
ExecutionContext.scala
Supertypes
classObject
traitMatchable
classAny
Known subtypes

Contains factory methods for creating execution contexts.

Contains factory methods for creating execution contexts.

Attributes

Companion
trait
Source
ExecutionContext.scala
Supertypes
classObject
traitMatchable
classAny
Self type

AnExecutionContext that is also a JavaExecutor.

AnExecutionContext that is also a JavaExecutor.

Attributes

Source
ExecutionContext.scala
Supertypes
traitExecutor
classObject
traitMatchable
classAny
Known subtypes
traitFuture[+T] extendsAwaitable[T]

AFuture represents a value which may or may not be currently available, but will be available at some point, or an exception if that value could not be made available.

AFuture represents a value which may or may not be currently available, but will be available at some point, or an exception if that value could not be made available.

Asynchronous computations are created by callingFuture.apply, which yields instances ofFuture. Computations are executed using anExecutionContext, which is usually supplied implicitly, and which is commonly backed by a thread pool.

import ExecutionContext.Implicits.globalval s = "Hello"val f: Future[String] = Future {  s + " future!"}f foreach {  msg => println(msg)}

Note that theglobal context is convenient but restricted: "fatal" exceptions are reported only by printing a stack trace, and the underlying thread pool may be shared by a mix of jobs. For any nontrivial application, see the caveats explained atExecutionContext and also the overview linked below, which explainsexception handling in depth.

Attributes

See also
Companion
object
Source
Future.scala
Supertypes
traitAwaitable[T]
classObject
traitMatchable
classAny
Known subtypes
objectnever
objectFuture

Future companion object.

Future companion object.

Attributes

Companion
trait
Source
Future.scala
Supertypes
classObject
traitMatchable
classAny
Self type
Future.type
traitPromise[T]

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.

Attributes

Companion
object
Source
Promise.scala
Supertypes
classObject
traitMatchable
classAny
objectPromise

Attributes

Companion
trait
Source
Promise.scala
Supertypes
classObject
traitMatchable
classAny
Self type
Promise.type

Deprecated classlikes

classChannel[A]

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.

Type parameters

A

type of data exchanged

Attributes

Deprecated
[Since version 2.13.0]Use `java.util.concurrent.LinkedTransferQueue` instead.
Source
Channel.scala
Supertypes
classObject
traitMatchable
classAny
classDelayedLazyVal[T](f: ()=>T,body:=>Unit)(implicitexec:ExecutionContext)

ADelayedLazyVal is a wrapper for lengthy computations which have a valid partially computed result.

ADelayedLazyVal is 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, theapply method will stop recalculating it and return a fixed value from that point forward.

Value parameters

body

the computation to run to completion in another thread

f

the function to obtain the current value at any point in time

Attributes

Deprecated
[Since version 2.13.0]`DelayedLazyVal` Will be removed in the future.
Source
DelayedLazyVal.scala
Supertypes
classObject
traitMatchable
classAny

TheJavaConversions object provides implicit conversions supporting interoperability between Scala and Java concurrency classes.

TheJavaConversions object provides implicit conversions supporting interoperability between Scala and Java concurrency classes.

Attributes

Deprecated
[Since version 2.13.0]Use the factory methods in `ExecutionContext` instead
Source
JavaConversions.scala
Supertypes
classObject
traitMatchable
classAny
Self type

Attributes

Deprecated
[Since version 2.13.0]Superseded by `scala.concurrent.Batchable`
Source
Future.scala
Supertypes
traitBatchable
classObject
traitMatchable
classAny
Self type
classSyncChannel[A]

ASyncChannel allows one to exchange data synchronously between a reader and a writer thread.

ASyncChannel allows 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.

Attributes

Deprecated
[Since version 2.13.0]Use `java.util.concurrent.Exchanger` instead.
Source
SyncChannel.scala
Supertypes
classObject
traitMatchable
classAny
classSyncVar[A]

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.

Type parameters

A

type of the contained value

Attributes

Deprecated
[Since version 2.13.0]Use `java.util.concurrent.LinkedBlockingQueue with capacity 1` instead.
Source
SyncVar.scala
Supertypes
classObject
traitMatchable
classAny

Value members

Concrete methods

finaldefblocking[T](body:=>T):T

Used to designate a piece of code which potentially blocks, allowing the currentBlockContext to adjust the runtime's behavior.

Used to designate a piece of code which potentially blocks, allowing the currentBlockContext to adjust the runtime's behavior. Properly marking blocking code may improve performance or avoid deadlocks.

Blocking on anAwaitable should be done usingAwait.result instead ofblocking.

Value parameters

body

A piece of code which contains potentially blocking or long running calls.

Attributes

Throws

CancellationException if the computation was cancelled

InterruptedExceptionin the case that a wait within the blockingbody was interrupted

Source
package.scala
In this article
Generated with
Copyright (c) 2002-2025, LAMP/EPFL
Copyright (c) 2002-2025, LAMP/EPFL

[8]ページ先頭

©2009-2025 Movatter.jp