Table of contents
1.
Introduction
2.
Play and Thread 
3.
Play Execution Context
4.
Default Thread Pool 
5.
Configuring the Default & Using other Thread Pools
6.
Class Loaders
7.
Frequently Asked Questions
7.1.
What is Play Framework?
7.2.
What does Play Thread Pools mean?
7.3.
What happens when the thread pool is full?
7.4.
What are the advantages of thread pooling?
7.5.
How many types of thread pools are present in java?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Configuring Play Thread Pools

Author Gunjan Batra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

This blog will study how to configure your application's Play's Thread pools. You will be given insights into what thread pools are in play and why they are used in your application.

Play

You will further see different methods to configure the framework in your application. You will further understand how these thread pools are essential in your web- application.

Play and Thread 

Play framework is an asynchronous framework. Thread pools in play are used to increase your application's performance when you run many tasks in your application in a single go.

If you are doing a lot of extensive CPU usage, you must know which thread will be used to operate.

Thread Pool

Play has shown that when appropriately configured, it can manage and run tons of work without any problem and improve the application's working.

Play Execution Context

Execution Context is another name for Thread in PlayFramework. Play uses several thread pools for different purposes.

Play execution context

 Internal Thread pools: The server engine uses these internally for processing IO. Never permit a thread in one of these thread pools to run code from an application. Play is configured in either of the two ways.

 Akka HTTP server backend:  The Akka HTTP server backend is configured by default. Application.conf configuration settings must be used to modify the backend settings.

 Netty server backend: The Netty Server backend can be applied explicitly, whose configuration settings can also be configured from the application.conf.

Default Thread Pool 

Every function in Play Framework uses the default thread pool. In most situations, the thread pool uses the default thread pool method. Through @Inject(), you can access this (implicit ec: ExecutionContext)

 Include this in your scala source file.

class Samples @Inject() (components: ControllerComponents)(implicit ec: ExecutionContext)
    extends AbstractController(components) {
  def someAsyncAction = Action.async {
    someCalculation()
      .map { result =>
        Ok(s"The answer is $result")
      }
      .recover {
        case e: TimeoutException =>
          InternalServerError("Calculation timed out!")
      }
  }


  def someCalculation(): Future[Int] = {
    Future.successful(42)
  }
}


Use CompletionStage with an HttpExecutionContext in Java code:
 

import play.libs.concurrent.HttpExecutionContext;
import play.mvc.*;


import javax.inject.Inject;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;


public class MyController extends Controller {


  private HttpExecutionContext httpExecutionContext;


  @Inject
  public MyController(HttpExecutionContext ec) {
    this.httpExecutionContext = ec;
  }


  public CompletionStage<Result> index() {
    // Use a different task with explicit EC
    return calculateResponse()
        .thenApplyAsync(
            answer -> {
              return ok("answer was " + answer).flashing("info", "Response updated!");
            },
            httpExecutionContext.current());
  }


  private static CompletionStage<String> calculateResponse() {
    return CompletableFuture.completedFuture("42");
  }
}


This execution context uses the default dispatcher provided by Akka and connects directly to the application's actor system.

Configuring the Default & Using other Thread Pools

Under the Akka namespace in the application.conf, the default thread pool can be set up using the usual Akka configuration.

In some cases, you might want to distribute work to various thread pools in some situations. This could involve IO work, such as database access or CPU-intensive tasks. You must first establish a ThreadPool, which is simple to do in Scala:

val myExecutionContext: ExecutionContext = akkaSystem.dispatchers.lookup("my-context")


To configure this Akka executionContext, enable this configuration in the application.conf

my-context {
  fork-join-executor {
    parallelism-factor = 20.0
    parallelism-max = 200
  }
}


In scala, use the scala Future companion object function.

Future {
  // Some blocking or expensive code here
}(myExecutionContext)


Or include it implicitly.

implicit val ec = myExecutionContext
Future {
  // Some blocking or expensive code here
}

Class Loaders

Class loaders require more attention in a multithreaded environment.

Class loader

It's possible that the thread context class loader in a Play application won't always be able to load application classes. To load classes, you need to use the application class loader specifically.

Java

Class myClass = app.classloader().loadClass(myClassName);


Scala

val myClass = app.classloader.loadClass(myClassName)


Using this explicitly to load classes is a must when Play is in development mode and not in production. This is because play in development mode uses multiple class loaders for automatic application reloading.

When using third-party libraries, it might happen that sometimes you are unable to load class explicitly. At that time, it is guided that before you call the third party, you explicitly set the thread context class loader. Once you're done calling the outside code, restore the context class loader to its default setting.

Frequently Asked Questions

What is Play Framework?

It is an open-source web application framework that follows the MVC model structure. MVC stands for Model, View, and  Controller.

What does Play Thread Pools mean?

 Play is Configured with Akka HTTP server by default, so configuration settings from the application.conf. Play also has a second configuration known as the Netty Server backend.

What happens when the thread pool is full?

By default, the Max threads of the Thread pool are very high. So generally, your app will crash first, and even if the thread pool is complete, the new tasks are queued, and slowly Thread pools allocate the new threads.

What are the advantages of thread pooling?

Thread pools are easy to access. It helps to improve performance, and there is no need to create new threads repeatedly.

How many types of thread pools are present in java?

We have five types of thread pool executors with the pre-built methods in java. util.concurrent package.

Conclusion

 In this blog, we have discussed configuring Play Thread pools. We have further seen how this thread helps increase the application's performance. We have seen the configuration of Thread in Java and Scala. We have understood how class loaders work and their usage.

You can learn more about Play by visiting the Coding Ninjas Studio library or clicking the following links. Configuration file syntax and featuresDebugging-your-buildConfiguring-netty-server-backend.

Ninja

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses, refer to the mock test and problems; look at the interview experiences and interview bundle for placement preparations.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning, Ninjas!

Thankyou
Live masterclass