• Stars
    star
    1,138
  • Rank 39,558 (Top 0.9 %)
  • Language
    Scala
  • License
    Apache License 2.0
  • Created about 11 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An asynchronous programming facility for Scala

scala-async

A Scala DSL to enable a direct style of coding when composing Futures.

Usage

As of scala-async 1.0, Scala 2.12.12+ or 2.13.3+ are required.

Add dependency

SBT Example

libraryDependencies += "org.scala-lang.modules" %% "scala-async" % "1.0.1"
libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value % Provided

For Maven projects add the following to your (make sure to use the correct Scala version suffix to match your project’s Scala binary version):

Maven Example

<dependency>
  <groupId>org.scala-lang.modules</groupId>
  <artifactId>scala-async_2.13</artifactId>
  <version>1.0.1</version>
</dependency>
<dependency>
  <groupId>org.scala-lang</groupId>
  <artifactId>scala-reflect</artifactId>
  <version>2.13.8</version>
  <scope>provided</scope>
</dependency>

Enable compiler support for async

Add the -Xasync to the Scala compiler options.

SBT Example

scalacOptions += "-Xasync"

Maven Example

<project>
  ...
  <plugin>
    <groupId>net.alchim31.maven</groupId>
    <artifactId>scala-maven-plugin</artifactId>
    <version>4.4.0</version>
    <configuration>
      <args>
        <arg>-Xasync</arg>
      </args>
    </configuration>
  </plugin>
  ...
</project>

Start coding

import scala.concurrent.ExecutionContext.Implicits.global
import scala.async.Async.{async, await}

val future = async {
  val f1: Future[Boolean] = async { ...; true }
  val f2 = async { ...; 42 }
  if (await(f1)) await(f2) else 0
}

What is async?

async marks a block of asynchronous code. Such a block usually contains one or more await calls, which marks a point at which the computation will be suspended until the awaited Future is complete.

By default, async blocks operate on scala.concurrent.{Future, Promise}. The system can be adapted to alternative implementations of the Future pattern.

Consider the following example:

def slowCalcFuture: Future[Int] = ...             // 01
def combined: Future[Int] = async {               // 02
  await(slowCalcFuture) + await(slowCalcFuture)   // 03
}
val x: Int = Await.result(combined, 10.seconds)   // 05

Line 1 defines an asynchronous method: it returns a Future.

Line 2 begins an async block. During compilation, the contents of this block will be analyzed to identify the await calls, and transformed into non-blocking code.

Control flow will immediately pass to line 5, as the computation in the async block is not executed on the caller's thread.

Line 3 begins by triggering slowCalcFuture, and then suspending until it has been calculated. Only after it has finished, we trigger it again, and suspend again. Finally, we add the results and complete combined, which in turn will release line 5 (unless it had already timed out).

It is important to note that while lines 1-4 are non-blocking, they are not parallel. If we wanted to parallelize the two computations, we could rearrange the code as follows:

def combined: Future[Int] = async {
  val future1 = slowCalcFuture
  val future2 = slowCalcFuture
  await(future1) + await(future2)
}

Limitations

await must be directly in the control flow of the async expression

The await cannot be nested under a local method, object, class or lambda:

async {
  List(1).foreach { x => await(f(x) } // invalid
}

await must be not be nested within try / catch / finally.

This implementation restriction may be lifted in future versions.

Comparison with direct use of Future API

This computation could also be expressed by directly using the higher-order functions of Futures:

def slowCalcFuture: Future[Int] = ...
val future1 = slowCalcFuture
val future2 = slowCalcFuture
def combined: Future[Int] = for {
  r1 <- future1
  r2 <- future2
} yield r1 + r2

The async approach has two advantages over the use of map and flatMap:

  1. The code more directly reflects the programmer's intent, and does not require us to name the results r1 and r2. This advantage is even more pronounced when we mix control structures in async blocks.
  2. async blocks are compiled to a single anonymous class, as opposed to a separate anonymous class for each closure required at each generator (<-) in the for-comprehension. This reduces the size of generated code, and can avoid boxing of intermediate results.

More Repositories

1

scala

Scala 2 compiler and standard library. Bugs at https://github.com/scala/bug; Scala 3 at https://github.com/scala/scala3
Scala
14,269
star
2

scala3

The Scala 3 compiler, also known as Dotty.
Scala
5,686
star
3

pickling

Fast, customizable, boilerplate-free pickling support for Scala
Scala
833
star
4

scala-parser-combinators

simple combinator-based parsing for Scala. formerly part of the Scala standard library, now a separate community-maintained module
Scala
642
star
5

docs.scala-lang

The Scala Documentation website
HTML
551
star
6

scala-java8-compat

A Java 8 (and up) compatibility kit for Scala.
Scala
436
star
7

legacy-svn-scala

OBSOLETE, we're over there:
Scala
366
star
8

scala3-example-project

An example sbt project that compiles using Dotty
Scala
332
star
9

scala-xml

The standard Scala XML library
Scala
292
star
10

scala-dist

sbt project that packages the Scala distribution
Scala
276
star
11

scala-lang

sources for the Scala language website
SCSS
259
star
12

scala-abide

obsolete; visit https://github.com/scalacenter/scalafix instead
Scala
232
star
13

bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
230
star
14

collection-strawman

Implementation of the new Scala 2.13 Collections
Scala
201
star
15

scala-collection-compat

makes some Scala 2.13 APIs (primarily collections, also some others) available on 2.11 and 2.12, to aid cross-building
Scala
200
star
16

scala-parallel-collections

Parallel collections standard library module for Scala 2.13+
Scala
194
star
17

scala-seed.g8

Giter8 template for a simple hello world app in Scala.
Scala
146
star
18

scala-dev

Scala 2 team issues. Not for user-facing bugs or directly actionable user-facing improvements. For build/test/infra and for longer-term planning and idea tracking. Our bug tracker is at https://github.com/scala/bug/issues
132
star
19

community-build

Scala 2 community build — a corpus of open-source repos built against Scala nightlies
Shell
129
star
20

scala-swing

Scala wrappers for Java's Swing API for desktop GUIs
Scala
126
star
21

scala3.g8

Scala
123
star
22

scala-collection-contrib

community-contributed additions to the Scala 2.13 collections
Scala
106
star
23

scala-module-dependency-sample

Depend on Scala modules like a pro
Scala
95
star
24

scala-continuations

the Scala delimited continuations plugin and library
Scala
89
star
25

make-release-notes

The project that generates Scala release notes.
HTML
85
star
26

toolkit

The batteries-included Scala
Scala
81
star
27

vscode-scala-syntax

Visual Studio Code extension for syntax highlighting Scala sources
Scala
72
star
28

compiler-benchmark

Benchmarks for scalac
Scala
68
star
29

slip

obsolete — archival use only
68
star
30

scala-library-next

backwards-binary-compatible Scala standard library additions
Scala
66
star
31

improvement-proposals

Scala Improvement Proposals
42
star
32

scala.epfl.ch

web site for the Scala Center @ EPFL in Switzerland
SCSS
37
star
33

scala-tool-support

XML
34
star
34

hello-world.g8

Scala
27
star
35

scala-collection-laws

partially-automatic generation of tests for the entire collections library
Scala
21
star
36

scala3-cross.g8

Scala
17
star
37

scabot

Scala's PR&CI automation bot
Scala
14
star
38

sbt-scala-module

sbt plugin for scala modules.
Scala
14
star
39

scala-jenkins-infra

A Chef cookbook that manages Scala's CI infrastructure.
Shell
14
star
40

scalatest-example.g8

Scala
13
star
41

scala3-mill-example-project

Shell
12
star
42

scala-asm

A fork of https://gitlab.ow2.org/asm/asm for the Scala compiler
12
star
43

compiler-interface

a binary contract between Zinc and Scala Compilers
Scala
10
star
44

scala-partest

Legacy repo for testing framework for Scala versions <= 2.12
Scala
9
star
45

scala-asm-legacy

A fork of asm.ow2.org for the Scala compiler
Java
8
star
46

scala3-staging.g8

Scala
7
star
47

scala-modules-build

Build support for the various Scala Modules
Shell
1
star
48

actors-migration

Scala
1
star
49

scala-partest-interface

SBT interface to partest
1
star
50

scala-library-all

Conglomerate pom file to pull in components of Scala standard library easily.
Scala
1
star
51

scala-dist-smoketest

Smoke Test for newly created Scala distributions
Shell
1
star
52

scala3-tasty-inspector.g8

Scala
1
star