Friday 15 March 2019

About Executor Framework

Executor Framework


Java Concurrency API defines below three executor interfaces that covers everything that is needed for creating and managing threads: -

Executors Framework - This is a framework for creating and managing threads. 

Executor - A simple interface for executing tasks or A simple interface that contains a method called execute () to launch a task specified by a Runnable object.

ExecutorService -  A more complex interface which contains additional methods for managing the tasks and the executor itself or A sub-interface of Executor that adds functionality to manage the lifecycle of the tasks. It also provides a submit () method whose overloaded versions can accept a Runnable as well as a Callable object. Callable objects are similar to Runnable except that the task specified by a Callable object can also return a value.

ScheduledExecutorService - Extends ExecutorService with methods for scheduling the execution of a task or A sub-interface of ExecutorService. It adds functionality to schedule the execution of the tasks.


Executors framework helps to do following:


To Create a Group of Threads: We can create threads using the available various methods, more specifically a pool of threads, that your application can use to run the appropriate tasks concurrently.

Thread Management: It manages the life cycle of the threads in the thread pool. You don’t need to worry about whether the threads in the thread pool are active or busy or dead before submitting a task for execution.

Task submission and execution: Executors framework provides methods for submitting tasks for execution in the thread pool, and also gives us the provision to decide when the tasks will be executed. For example, you can submit a task to be executed now or schedule them to be executed later or make them execute periodically.


Q:How to Create an Executor?

If you want to create an Executor, it is possible to use Executors class factory methods. Below are the most common methods, which are used to create Executors:

An ExecutorService with a single thread to execute commands with method newSingleThreadExecutor.

A ScheduledExecutorService with a single thread to execute commands with the method newSingleThreadScheduledExecutor.

An ExecutorService that use a fixed length pool of threads to execute commands with the method newFixedThreadPool.

An ExecutorService with a pool of threads that creates a new thread if no thread is available and reuse an existing thread if they are available with newCachedThreadPool.

        A ScheduledExecutorService with a fixed length pool of threads to execute scheduled commands with the method newScheduledThreadPool.


Here are examples to creates ExecutorService and ScheduledExecutorService instances:

// Creates a single thread ExecutorService
1) ExecutorService singleExecutorService = Executors.newSingleThreadExecutor();

// Creates a single thread ScheduledExecutorService
2) ScheduledExecutorService singleScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

// Creates an ExecutorService that use a pool of 5 threads
3) ExecutorService fixedExecutorService = Executors.newFixedThreadPool(5);

// Creates an ExecutorService that use a pool that creates threads on demand and that kill them after 60 seconds if they are not used
4) ExecutorService onDemandExecutorService = Executors.newCachedThreadPool();

// Creates a ScheduledExecutorService that use a pool of 5 threads
5) ScheduledExecutorService fixedScheduledExecutorService = Executors.newScheduledThreadPool(5);




A complete example to convert JSON file into Java Objects

JSON to Java Conversion

      Maven Dependency required for this project

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.6</version>
    </dependency>

Conversion from JSON to JAVA object takes place by following below two steps,


  •        By Creating instance of com.fasterxml.jackson.databind.ObjectMapper
  •        Then using objectMapper.readValue() method to convert JSON to Java object


ObjectMapper mapper = new ObjectMapper();
allQuestions =  mapper.readValue(new File("questions.json"), AllQuestions.class);


Complete Example:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gaurav.json</groupId>
<artifactId>jackson-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>
 <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.6</version>
    </dependency>
</dependencies>
</project>

Java Pojo Classes:

AllQuestions.java


package com.gaurav.jackson.model;
public class AllQuestions
{
    private Questions[] questions;
    public Questions[] getQuestions ()
    {
        return questions;
    }
    public void setQuestions (Questions[] questions)
    {
        this.questions = questions;
    }
    @Override
    public String toString()
    {
        return "AllQuestions [questions = "+questions+"]";    }
}



Questions.java


package com.gaurav.jackson.model;
public class Questions
{
    private String questionIdId;
    private QuestionDetails questionDetails;
    public String getQuestionIdId ()
    {
        return questionIdId;    }
    public void setQuestionIdId (String questionIdId)
    {
        this.questionIdId = questionIdId;
    }
    public QuestionDetails getQuestionDetails ()
    {
        return questionDetails;    }
    public void setQuestionDetails (QuestionDetails questionDetails)
    {
        this.questionDetails = questionDetails;    }
    @Override
    public String toString()
    {
        return "Questions [questionIdId = "+questionIdId+", questionDetails = "+questionDetails+"]";    }
}



QuestionDetails.java


package com.gaurav.jackson.model;
public class QuestionDetails
{
    private String data;
    private String index;
    private String exam_id;
    public String getData ()
    {
        return data;
    }
    public void setData (String data)
    {
        this.data = data;
    }
    public String getIndex ()
    {
        return index;
    }
    public void setIndex (String index)
    {
        this.index = index;
    }
    public String getExam_id ()
    {
        return exam_id;
    }
    public void setExam_id (String exam_id)
    {
        this.exam_id = exam_id;
    }
    @Override
    public String toString()
    {
        return "QuestionDetails [data = "+data+", index = "+index+", exam_id = "+exam_id+"]";    }
}

  • Main Java class which will help to read the JSON file and convert that into Java object.



JSON2JavaConverter.java
package com.gaurav.jackson.json;
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.gaurav.jackson.model.AllQuestions;
import com.gaurav.jackson.model.QuestionDetails;
import com.gaurav.jackson.model.Questions;
public class JSON2JavaConverter {
public static void main(String[] args) {
  AllQuestions allQuestions = null;
        ObjectMapper mapper = new ObjectMapper();
        try         {
        allQuestions =  mapper.readValue(new File("questions.json"), AllQuestions.class);
        } catch (JsonGenerationException e)
        {
          e.printStackTrace();
        } catch (JsonMappingException e)
        {
          e.printStackTrace();
        } catch (IOException e)
        {
          e.printStackTrace();
        }
            Questions[] quesArray = allQuestions.getQuestions();
        for(Questions question: quesArray) {
        QuestionDetails questionDetails = question.getQuestionDetails();
        System.out.println("questionDetail Exam ID:"+questionDetails.getExam_id());
        System.out.println("questionDetail Index:"+questionDetails.getIndex());
        System.out.println("questionDetail Data:"+questionDetails.getData());
        }
        }
}


OUTPUT:


questionDetail Exam ID:2345190
questionDetail Index:0
questionDetail Data:{"Which of the following was most probably the first metal to be used in India?", "answers": "[A] Iron", "[B] Copper", "[C] Gold"," [D] Silver", " Answer is": "[B] Copper"}
questionDetail Exam ID:2345191
questionDetail Index:1
questionDetail Data:{"Entomology is the science that studies?", "answers": "[A] Behavior of human beings", "[B] Insects", "[C] The origin and history of technical and scientific terms"," [D] The formation of rocks", " Answer is": "[B] Insects"}
questionDetail Exam ID:2345190
questionDetail Index:2
questionDetail Data:{"For galvanizing iron which of the following metals is used?", "answers": "[A] Aluminium", "[B] Copper", "[C] Lead"," [D] Zinc", " Answer is": "[D] Zinc"}