TechWriterDev
  • Cloud
    • AWS
      • 00_Doubts
      • CloudPractitioner
        • Cloud Computing
        • AWS Global Infrastructure
        • Introduction to AWS EC2
        • Elastic load balancer(ELB)
        • 04_Messaging_Queuing
        • Aditional Computing Service
        • Accessing AWS resources
        • AWS Networking
        • Storage
        • Amazon Database Solutions
        • Monitoring Tools
        • AWS Security
        • Distributed Denial Of Service Attacks
      • DeveloperAssociate
        • References
        • AWS DVA-C02 Services Index
        • Services
          • 00_IAM
            • Identity and Access Management (IAM)
            • Account Protection Mechanisms
            • Access Mechanism of AWS Resources
            • Security Tools
            • Responsibility Model
            • Advanced Concepts
          • 01_EC2
            • Elastic Compute Cloud (EC2)
            • EC2 Volume Types
            • Amazon Machine Image (AMI)
            • AWS charges for IPv4 address
          • 02_SecurityGroups
            • Security Groups
          • 03_Elastic_LoadBalancing
            • Terminology
            • Elastic load balancer
            • Features
            • Basics
          • 04_AutoScaling
            • Auto Scaling
          • 05_RDS
            • Relational Database Service (RDS)
            • Aurora
            • Security
            • RDS Proxy
          • 06_ElastiCache
            • Cache
            • Cache Offerings
          • 07_Route53
            • Basics of DNS
            • Route 53
          • 08_VPC
            • Virtual Private Cloud (VPC)
          • 09_S3
            • Simple Storage Service (S3)
            • S3 Features
            • S3 Encryption
            • S3 Features
            • S3 Bucket Policy and IAM Policy
          • 10_ECS
            • Elastic Container Service (ECS)
            • Elastic Container Registry (ECR)
            • AWS Copilot
          • 11_EKS
            • Elastic Kubernetes Service (EKS)
          • 12_SDK_CLI_Tips
            • Access AWS Resources
          • 13_CloudFront
            • Cloud Front
          • 14_Messaging
            • Simple Queue Service (SQS)
            • Simple Notification Service (SNS)
            • Fan Out Pattern
            • Kinesis
            • Compare and Contrast
          • 15_ElasticBeanStalk
            • Elastic Beanstalk
          • 16_CloudFormation
            • CloudFormation
            • Dynamic References
          • 17_Monitoring
            • AWS Monitoring
            • AWS CloudWatch
            • CloudWatch Alarms
            • Synthetics Canary
            • Amazon EventBridge (formerly CloudWatch Events)
            • X-Ray
            • OpenTelemetry
            • CloudTrail
          • 18_Lambda
            • Lambda
            • Lambda Integrations
            • Configuring Lambda
            • Lambda Layers
          • 19_API_Gateway
            • API Gateway
            • API Gateway Integrations
          • 20_DynamoDB
            • DynamoDB
            • Operations
            • Indexes
            • DynamoDB Accelerator (DAX)
            • DynamoDB Streams
            • Transactions
            • Integrations
          • 21_CICD
            • CICD
            • CodeCommit
            • CodePipeline
            • CodeBuild
            • CodeDeploy
            • CodeArtifact
            • CloudGuru
          • 22_SAM
            • Serverless Application Model (SAM)
          • 23_CDK
            • Cloud Development Kit (CDK)
          • 24_StepFunctions
            • Step Functions
            • Types of step function
          • 25_AppSync
            • AppSync
          • 26_Amplify
            • Amplify
          • 27_STS
            • Security Token Service (STS)
          • 28_DirectoryService
            • Active Directory
          • 29_KMS
            • Encryption
            • KMS API
            • Features
            • Cloud Hardware Security Module (HSM)
          • 30_SSM_Store
            • SSM Parameter Store
          • 31_SecretsManager
            • Secrets Manager
          • 32_Cognito
            • Cognito
      • Questions
        • AWS_Region
        • EC2
        • IAM
  • Database
    • MongoDb
      • Mongo db Basics
      • Mongo DB Atlas
      • Document
      • Import-Export based on Data Format
      • Mongo Shell Commands
      • Query Operators
      • Indexes
      • Upsert
      • MongoDB Aggregation Framework
      • Aggregation Framework Operators
    • PostgreSQL
      • POSTGRE SQL DataTypes
      • About table
      • Constraints
  • Technologies
    • RabbitMQ
      • RabbitMQ Concepts
      • Introduction to Exchanges
      • Introduction to Queues
    • Terraform
      • 00_Introduction
      • Configuration blocks
      • Commands
      • Variables
      • Terraform Cloud
      • Modules
  • Languages
    • Java
      • Logging
        • Getting Started
      • 00_Core
        • 00_Basics
          • Java Vs C++
          • Object oriented principles
          • Steps to compile a java program
          • JVM Internals
          • Understanding Java Development Kit
          • What is JIT Compiler?
          • Java data types
          • 07_identifiers_type_conversion
          • 08_references_and_packages
          • Steps for attaching scanner
        • Concurrency
          • 00_Threads
            • Threads
          • 01_ExecutorFramework
            • Executor Framework
            • Asynchronous Computation
      • 01_Backend
        • 01_HttpAndWebServerBasics
          • HTTP
          • Content Type
          • Web Server
        • 02_J2EE_Basics
          • J2EE_Basics
          • Why HttpServlet classs is declared as abstract class BUT with 100 % concrete functionality ?
        • 03_TomCatAndSession
          • What is a Session?
          • WebContainer
        • 04_PageNavigation
          • Cookies Additional Information
          • Page Navigation Techniques
        • 05_AboutServlet
          • CGI v/s Servlet
          • Executor Framework
          • Servlet Life cycle
          • SERVLET CONFIG
          • Servlet Context
          • Servlet Listener (web application listener)
        • 08_SpringBoot
          • Spring Boot
          • Some common annotations used in spring eco system
        • 09_SpringDataJPA
          • Spring Data JPA
        • Java_Language_Changes
          • JDK enhancement tracking reference
        • 06_ORM_Hibernate
          • readmes
            • Hibernate
            • Advantages of Hibernate
            • Hibernate Caching
            • Hibernate API
            • Hibernate Query API
            • Hibernate Annotations and JPQL
            • Entity and Value Type
        • 07_SpringFramework
          • bean_validation
            • Bean Validation
          • core
            • readme
              • Spring
              • Spring Framework Modules
              • Spring MVC Request flow
              • Dependency Injection
              • Spring Beans
              • 06_Spring_Framework_Annotations
      • 03_Tools
        • Maven
          • Maven
  • SoftwareEngineering
    • DesignPatterns
      • Notes
        • Basics
        • OOP
        • SOLID Principles
        • 03_Creational
          • Abstract Factory (aka Kit)
          • Builder
          • Factory Method (aka Virtual constructor)
          • Prototype
          • Singleton
        • 04_Structural
          • Adapter (aka Wrapper)
          • Bridge (aka Handle | Body)
          • Composite
          • Decorator (aka Wrapper)
          • Facade
          • Flyweight
          • Proxy (aka Surrogate)
        • 05_Behavioral
          • Chain of Responsibility
          • Command (aka Action | Transaction)
          • Iterator (aka Cursor)
          • Observer (aka Publish-Subscribe | Dependents)
          • Strategy (aka Policy)
    • Principles
      • REST
        • REST
  • Tools
    • Containers
      • Docker
        • Docker
        • Docker Image
        • Commands
        • Compose
        • Best Practices
      • Kubernetes
        • Kubernetes
    • VCS
      • Git
        • Quick reference of useful Git commands
Powered by GitBook
On this page
  1. Languages
  2. Java
  3. 01_Backend
  4. 05_AboutServlet

Executor Framework

PreviousCGI v/s ServletNextServlet Life cycle

Last updated 4 months ago

  • Introduced in Java 5.

  • Why Executor Framework?

    • If you have thousands of task to be executed and if you create each thread for thousands of tasks, you will get performance overheads as creation and maintenance of each thread is an overhead.

    • Executor framework solves this problem.

    • In executor framework, you can create specified number of threads and reuse them to execute more tasks once it completes its current task.

    • It simplifies the design of creating multithreaded application and manages thread life cycles.

    • The programmer does not have to create or manage threads themselves, that’s the biggest advantage of executor framework.

  • Important classes/interfaces for executor framework.

    • java.util.concurrent.Executor

      • This interface is used to submit new task. It has a method called execute().

          public interface Executor {
          void execute(Runnable task);
          }
    • java.util.concurrent.ExecutorService

      • It is sub-interface of Executor.

      • Provides methods for submitting/executing Callable/Runnable tasks, shutting down service, executing multiple tasks etc.

      • Read about callable task

    • java.util.concurrent.ScheduledExecutorService

    • It is sub-interface of executor service which provides methods for scheduling tasks at fixed intervals/delay along with initial delay.

    • java.util.concurrent.Executors

      • This class provides factory methods for creating thread pool based executors.

        • Important factory methods (static method returning instance of ExecutorService) of Executors are:

          • newFixedThreadPool

            • This method returns thread pool executor whose maximum size is fixed. If all nthreads are busy performing the task and additional tasks are submitted, then they will have to wait in the task queue until thread is available.

            • The core pool size determines how many threads (idle) will be created when the web container starts. Max pool size is the maximum number of threads that can be created by the web container.

            • server.xml consists of the executor framework related configuration in tomcat server.

            • Once a servicing is done for a client request, the pooled out thread is returned back to pool, rather than killing the thread. This approach helps in reusable thread management.

            • Note, once the core pool size is reached a new thread is added to thread pool.

            • If all the threads are busy servicing the clients, then new client request will be added to task queue and will be waiting for free thread. Once a free thread becomes available, then the queued task will be allocated the free thread and request will be further processed.

            • If the task queue also becomes full, then new connections are rejected untill current requests are processed and thread becomes available or task queue gets emptied.

            • Once the server is shutdown all these are destroyed and resources are cleaned up.

          • newCachedThreadPool

            • This method returns an unbounded thread pool. It doesn’t have maximum size but if it has less number of tasks, then it will tear down unused thread. If a thread has been unused for keepAliveTime (60 seconds), then it will tear it down.

          • newSingleThreadedExecutor

            • This method returns an executor which is guaranteed to use the single thread.

          • newScheduledThreadPool

            • This method returns a fixed size thread pool that can schedule commands to run after a given delay, or to execute periodically.

Steps for Runnable

  1. Create a thread-pool executor, using suitable factory method of Executors.

eg : For fixed no of threads ExecutorService executor = Executors.newFixedThreadPool(10);

  1. Create Runnable task

  2. Use inherited method public void execute(Runnable command) Executes this Runnable task , in a separate thread.

  3. Shutdown the service public void shutdown()

  • Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

  1. boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs.

  2. List shutdownNow()

  • Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.


BUT disadvantages with Runnable interface

  1. Can't return result from the running task

  2. Doesn't include throws Exception .

Better API java.util.concurrent.Callable V : result type of call method Represents a task that returns a result and may throw an exception. Functional i/f SAM : public V call() throws Exception Computes a result, or throws an exception if unable to do so.

Steps in using Callable i/f

  1. Create a thread-pool executor , using suitable factory method of Executors.

eg : For fixed no of threads ExecutorService executor = Executors.newFixedThreadPool(10);

  1. Create Callable task , which returns a result.

  2. To submit a task to executor service , use method of ExecutorService i/f : public Future submit(Callable task) Submits a value-returning task for execution and returns a Future representing the pending results of the task. It's a non blocking method (i.e rets immediately)

The Future's get method will return the task's result upon successful completion.

If you would like to immediately block waiting for a task, invoke get() on Future. eg : result = exec.submit(aCallable).get();

OR main thread can perform some other jobs in the mean time & then invoke get on Future , to actually get the results. (get : blocking call ,waits till the computation is completed n then rets result)

  1. Other methods of ExecutorService i/f

public List<Future> invokeAll(Collection<? extends Callable> tasks) throws InterruptedException

It's a blocking call.(waits till all tasks are complete) Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone() is true for each element of the returned list.

  1. Shutdown the service public void shutdown() Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

  2. boolean awaitTermination(long timeout,TimeUnit unit) throws InterruptedException Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs.

  3. List shutdownNow() Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.