DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Page Object Model for Performance Testing With Gatling
  • Overview of C# Async Programming
  • [CSF] OfficeFloor: Going Beyond Dependency Injection
  • Pattern Match Anything in Scala

Trending

  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • Code Reviews: Building an AI-Powered GitHub Integration
  • Apple and Anthropic Partner on AI-Powered Vibe-Coding Tool – Public Release TBD
  • Agile’s Quarter-Century Crisis
  1. DZone
  2. Coding
  3. Languages
  4. Executor and Execution Context Objects in Scala

Executor and Execution Context Objects in Scala

Learn more about Executor and Execution Context objects in Scala.

By 
Jashan Goyal user avatar
Jashan Goyal
·
Nov. 14, 19 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
15.3K Views

Join the DZone community and get the full member experience.

Join For Free

Executor Context Objects

Learn more about Executor and Execution Context objects in Scala.

Thread and Runnable have been around for a long time as two of the first concurrent execution approaches in Scala. Creating a new Thread takes less computational time compared to creating a new JVM process. We cannot afford to create a fresh Thread for each of these tasks, because if an application performs a large number of small concurrent tasks, then it requires high throughput.

You may also like: A Scalable Java Thread Pool Executor

In this post, we are going to discuss the Executor and Execution Context objects with specific code examples. Let's get started.

java7-concurrency-11-638

Thread Pools

Starting a Thread required us to allocate a memory region for its call stack and context switch from one Thread to another. But this consumes much more time than work in the concurrent task. For this reason, most concurrency frameworks have facilities that maintain a set of Threads in a waiting state and start running when concurrently executable work tasks become available. Generally, we call such facilities Thread pools.

To allow programmers to encapsulate the decision of how to run concurrently executable work tasks, the JDK comes with an abstraction called Executor. The Executor is an interface, and in this, a single execute method is defined. This method takes a runnable object and calls its run method.

ForkJoinPool

ForkJoinPool is an Executor introduced in JDK 7.  Its threads are daemons by default, which means there is no need to shut it down explicitly at the end of the program. Scala programmers can use it in JDK 6 by importing scala.concurrent.forkjoin package. Let’s see the implementation and submit tasks that can be asynchronously executed. 

In this code, first, we import the package and instantiate ForkJoinPool class and assign it to the executor. Now, this executor sent the task in the form of a runnable object that prints to the standard output. Finally, we use Thread.sleep to prevent the daemon threads in the ForkJoinPool instance from being terminated.

ExecutorService

It is the subtype of Executor interface which also implemented by the ForkJoinPool class. ExecutorService extends Executor which defines convenience methods. In this, I will talk about the shutdown method, this method makes sure that the Executor object terminates by all executing all the submitted tasks and then stopping all the worker threads. When your program no longer needs the ExecutorService object you created, you should ensure that the shutdown method is called.

In the above example, we used the sleep method. To prevent this, we can use the awaitTermination method. This method specifies the maximum amount of time to wait for their completion. Let’s see the example (this code is a continuation of the above code).

import java.util.concurrent.TimeUnit
executor.shutdown()
executor.awaitTermination(60, TimeUnit.SECONDS)


Execution Context

If you are a Scala programmer, then you know that the scala.concurrent package defines the ExecutionContext trait and offers similar functionality to that of the Executor objects. Many Scala methods take ExecutionContext objects as implicit parameters. It implements the abstract execute method, which perfectly corresponds to the execute method on the Executor interface and the reportFailure method. The ExecutorContext companion object contains the default execution called global, which internally uses a ForkJoinPool instance. With this, we can pass the parameter or import the package. 

Let’s look at an example:

object ExecutionContextGlobal extends App {
val ectx = ExecutionContext.global
ectx.execute(new Runnable {
def run() = log("Running on the execution context.")
})
Thread.sleep(500)
}


In this example, we instance the global to ectx and then send the task in the form of a Runnable object.

By importing the package:

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
val fut = Future { Thread.sleep(10000); 21 + 21 }


In this example, we imported global to globally, which means we don’t need to instance global again and again.

Thank you for reading to the end. If you liked this post, please do show your appreciation by giving it a like and sharing this blog. And don't forget to share your feedback in the comments.

Further Reading

A Scalable Java Thread Pool Executor

Java Multi-Threading With the ExecutorService

Object (computer science) Executor (software) Scala (programming language) Execution (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Page Object Model for Performance Testing With Gatling
  • Overview of C# Async Programming
  • [CSF] OfficeFloor: Going Beyond Dependency Injection
  • Pattern Match Anything in Scala

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!