Showing posts with label CoreJava. Show all posts
Showing posts with label CoreJava. Show all posts

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"}

Tuesday, 8 November 2016

Composition v/s Inheritance : Which should be preferable?



Composition V/S Inheritance





Inheritance is an "is-a" relationship where as Composition is a "has-a".
Composition allows reuse of code without extending it but in case of Inheritance we must extend the class for any reuse of code or functionality.


  • With Inheritance we are defining which class we are going to extend means static binding and this can’t be changed at runtime but with Composition we just define an object type which we want to use, which can hold its different implementation during execution means dynamic binding. So we can say that using Composition is more flexible than Inheritance.

  • In case of Inheritance we can extend only one class but if we want to take advantage of multiple class functionality then we can use Composition

  • At some point of time, Inheritance breaks encapsulation because in case of Inheritance, sub class is dependent upon super class behavior and if parent classes are changed than child class will also get affected and as a result it breaks sub class functionality.


  • Composition also allows code reuse for final class and this is not possible in Inheritance because we can’t extend final class.

  •  When we are using Composition in our application then during unit testing it is easy to test because we are able to provide mock implementation of required classes but when we are using Inheritance then we required parent classes in order to test child classes and we can’t mock parent classes. 
Example of Composition and Inheritance-

Car.java

package com.inheritancecomposition.relationship;

public class Car {
    

/** Class/Instance members and Methods implementation */
    private int maxSpeed;
    private String color;

    public void setColor(String color) {
        this.color = color;
    }
    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public void carDescription(){
        System.out.println("The "+color + " color car is running at max Speed of " + maxSpeed);
    }
}


Engine.java

package com.inheritancecomposition.relationship;

public class Engine {
    public void start(){
        System.out.println("** Engine Started **");
    }
    public void stop(){
        System.out.println("** Engine Stopped **");
    }
}


Hyundai.java

package com.inheritancecomposition.relationship;

public class Hyundai extends Car{ 
/** Inheritance is used here */
    /**
     * Hyundai extends Car and thus inherits all methods from Car (except final
     * and static) Hyundai can also define all its specific functionality
     */

    public void hyundaiStartDemo(){
        Engine hyundaiEngine = new Engine(); /** Composition is used here */
        hyundaiEngine.start();
        }
}



RelationsDemo.java

package com.inheritancecomposition.relationship;

public class RelationsDemo {
    public static void main(String[] args) {
        Hyundai myHyundai = new Hyundai();
        myHyundai.hyundaiStartDemo();
        myHyundai.setColor("Carbon Grey");
        myHyundai.setMaxSpeed(200);
        myHyundai.carDescription();
    }
}


Result:-

** Engine Started **
The Carbon Grey color car is running at max Speed of 200

Wednesday, 30 September 2015

Java Memory Management

Memory Management Part-II


Question : - What a Garbage Collector will do?

Answer:- Let's talk about Garbage Collector jobs
                Things to Consider
  • Stop the application events :- Garbage Collector pauses the entire application and at that            point it collects garbage.
  • Memory Fragmentation :- Memory fragmentation is when most of your memory is allocated in a large number of non-contiguous blocks and leaving a good percentage of our total memory unallocated, but that is unusable for most typical scenarios. This results in out of memory exceptions,When garbage collector runs does it defrag the memory fragment            to once or leave it to the latest state. 
  • ThroughPut :– how quickly can it run and how quickly can it collect?
  • Multi Core :- Now we have multiple processors or multiple threads Pauses are the times when an application appears unresponsive because garbage collection is occurring.
  • Promptness is the time between when an object becomes dead and memory becomes available, which is very important for distributed systems, including RMI.

 Question:- What is the way of Direct memory access in java?

Answer:- Java HotSpot VM contains a “backdoor” that provides a number of low-level operations to control threads and memory directly. This backdoor class sun.misc.Unsafe which is widely used by JDK itself in packages like java.nio or java.util.concurrent. This class provides an easy way to look into HotSpot JVM internals and this class can also be used for profiling and development tools.

Division of  java memory pool


The heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. JVM Heap memory is physically divided into two parts –Young Generation and Old Generation.

  • Eden Space: The pool from which memory is initially allocated for most objects. Most initial objects allocated in Eden space.
  •  Survivor Space: The pool containing objects that have survived the garbage collection of the Eden space.
  •  Tenured Generation: The pool containing objects that have existed for some time in the survivor space.
  •  Non-heap memory: Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size.
  •  Permanent Generation: The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
  • Code Cache: The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.



For demonstartion how Garbage Collection works in Java

GarbageCollectionExample.java

package com.gaurav.memorymanagement;

import java.lang.reflect.Field;

import sun.misc.Unsafe;

public class GarbageCollectionExample {
private static Unsafe unsafe;
static {
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe) field.get(null);
} catch (Exception e) {
e.printStackTrace();
}
}

public static long addressOf(Object o) throws Exception {
Object array[] = new Object[] { o };
long baseOffset = unsafe.arrayBaseOffset(Object[].class);
int addressSize = unsafe.addressSize();
long objectAddress;
switch (addressSize) {
case 4:
objectAddress = unsafe.getInt(array, baseOffset);
break;
case 8:
objectAddress = unsafe.getLong(array, baseOffset);
break;
default:
throw new Error("unsupported address size: " + addressSize);
}
return (objectAddress);
}

public static void main(String args[]){
try{
for(int i=0; i< 40000; i++){
Object mine = new GCObjects();
long address = addressOf(mine);
System.out.println(address);
}
}catch(Exception e){
e.printStackTrace();
}
}
}

class GCObjects {
long data;
long a;
long aa;
long aaa;
long aaaa;
long aaaaa;
long aaaaaa;
long aaaaaaa;
long aaaaaaaa;
long aaaaaaaaa;
long aaaaaaaaaa;
long aaaaaaaaaaa;
long aaaaaaaaaaaa;
long aaaaaaaaaaaaa;
long aaaaaaaaaaaaaa;
long aaaaaaaaaaaaaaa;
long aaaaaaaaaaaaaaaa;
long aaaaaaaaaaaaaaaaa;

}


Execution process - For demonstartion how Garbage Collection works in Java

            Java -cp . com.gaurav.memorymanagement.GarbageCollectionExample > GarbageCollectionExampleOutput.csv

This command will create a CSV file, which we can open with Microsoft Excel and represent those data using line chart. The representation will look like follows :




Thursday, 27 August 2015

Java Memory Management

Memory Management - PART - 1


Memory Management in java is responsibility of garbage collector. Garbage Collection is not the only form of Memory Management in Java. Real-time Specification for Java (RTSJ) is also being used for Memory Management. These efforts were mainly dedicated to real-time and embedded programming in Java for which GC was not suitable - due to performance overhead.

Understanding JVM Memory Model is very important if we want to know the working process of Java Garbage Collection.

Types of Garbage Collector : -

  • Do nothing : - It might just decide never to run and never to do anything, no memory gets free but it do stills gurantee to not collecting live objects.

  • Reference Counting garbage collector : - COM programming environment is the best example of Reference Counting Garbage collector. COM application may call 2 functions. First is Add Ref and second is Release. Add Ref increments the count of the object and Release decrease the count. When count goes to zero then ref is no longer been used or we can say that A reference count is maintained for each object on the heap. When an object is first created and a reference to it is assigned to a variable, the object's reference count is set to one. When any other variable is assigned a reference to that object, the object's count is incremented. When a reference to an object goes out of scope or is assigned a new value, the object's count is decremented. Any object with a reference count of zero can be garbage collected. When an object is garbage collected, any objects that it refers to have their reference counts decremented. In this way the garbage collection of one object may lead to the subsequent garbage collection of other objects.

  • Mark and Sweep : - To determine which objects are no longer in use, the JVM intermittently runs mark-and-sweep algorithm. Garbage collector runs in 2 phases, In mark phase it is marking that memory is still alive or this algorithm traverses all object references, starting with the GC roots, and marks every object found as alive and in sweep phase all of the heap memory that is not occupied by marked objects is reclaimed. It is simply marked as free, essentially swept free of unused objects.

  • Copying - Copying garbage collectors move all live objects to a new area and the old area is known to be all free space. This is not following any separate Mark and Sweep phases Objects are copied(these objects are discovered by the traversal from the root nodes) to the new area on the fly and forwarding ponters are left in their old locations and these pointers allows the garbage collector to detect references to objects that have already been moved. The garbage collector can then assign the value of the forwarding pointer to the references so they point to the object's new location.

  • Generational - Copying collectors spend much of their time for copying the same long-lived objects again and again. In order to address this inefficiency Generational collectors work with grouping objects by age and garbage collecting younger objects more often than older objects. This approach works by dividing the heap into two or more sub-heaps, each of which serves one "generation" of objects. The youngest generation is garbage collected most often. As most objects are short-lived, only a small percentage of young objects are likely to survive their first collection. Once an object has survived a few garbage collections as a member of the youngest generation, the object is promoted to the next generation: it is moved to another sub-heap.

  • Incremental - Rather than attempting to find and discard all unreachable objects at each invocation an incremental garbage collector just attempts to find and discard a portion of the unreachable objects. Because only a portion of the heap is garbage collected at each invocation, each invocation should in theory run in less time. A garbage collector that can perform incremental collections, each of which is guaranteed to require less than a certain maximum amount of time, can help make a Java virtual machine suitable for real-time environments.  


Reference taken from other sources