Book Image

Learning Concurrent Programming in Scala

By : Aleksandar Prokopec
5 (1)
Book Image

Learning Concurrent Programming in Scala

5 (1)
By: Aleksandar Prokopec

Overview of this book

Table of Contents (18 chapters)
Learning Concurrent Programming in Scala
Credits
Foreword
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Promises


In Chapter 2, Concurrency on the JVM and the Java Memory Model, we implemented an asynchronous method that used a worker thread and a task queue to receive and execute asynchronous computations. That example should have left you with a basic intuition about how the execute method is implemented in execution contexts. You might be wondering how the Future.apply method can return and complete a Future object. We will study promises in this section to answer this question. Promises are objects that can be assigned a value or an exception only once. This is why promises are sometimes also called single-assignment variables. A promise is represented with the Promise[T] type in Scala. To create a promise instance, we use the Promise.apply method on the Promise companion object:

def apply[T](): Promise[T]

This method returns a new promise instance. Like the Future.apply method, the Promise.apply method returns immediately; it is non-blocking. However, the Promise.apply method does not start...