Java Memory Model – Memory and Garbage Collection

Java Memory Model – Explained
Java memory model defines how the JVM works in our system. It is vital to understand how the Java memory model works to write the programs. Let us see in details about Java memory model

 

Difference between Heap and Stack

Heap Memory

Stack Memory

Store objects

Store local variables and function call

Has the actual object

Will have reference to the objects in the Heap Memory

OutOfMemory Error

StackOverFlow error when stack is full

All thread can access all objects in the Heap

Only owner thread can access the variables in the Stack

Young Generation:
The young generation is the place where all the new objects are created. When the young generation is filled, garbage collection is performed. This garbage collection is called Minor GC. Young Generation is divided into three parts – Eden Memory and two Survivor Memory spaces.

Important Points:
Most of the newly created objects are located in the Eden memory space.

  • When Eden space is filled with objects, Minor GC is performed and all the survivor objects are moved to one of the survivor spaces.

  • Minor GC also checks the survivor objects and move them to the other survivor space. So at a time, one of the survivor space is always empty.

  • Objects that are survived after many cycles of GC, are moved to the Old generation memory space. Usually, By setting an age for the young generation objects before they become eligible to promote to Old generation.

PermGen space:
Stores class related data, and is used to keep information for loaded classes and few other advanced features like StringPool.

MetaSpace: (From 1.8, instead of perm gen)

  • Are part of native memory – OS level
  • Metaspace by default increases its size , To the limit of OS, while PermGen always has a fixed maximum size.
  • No more out of memory error
  • We can set the size of metaspace and also it increases automatically, but permgen wont increase by itself
  • Garbage collection of the dead classes and classloaders is triggered once the class metadata usage reaches the MaxMetaspaceSize.

So where does static variables and static classes are stored? Is it heap or Permgen?

  • Since the heap has actual objects, static variables and static classes are stored in Permgen / Metaspace.

Eden and Survivor Space:

  • Most of the newly created objects are located in the Eden memory space.
  • When Eden space is filled with objects, Minor GC is performed and all the survivor objects are moved to one of the survivor spaces.
  • Minor GC also checks the survivor objects and move them to the other survivor space. So at a time, one of the survivor space is always empty.
  • Objects that are survived after many cycles of GC, are moved to the Old generation memory space. Usually, it’s done by setting a threshold for the age of the young generation objects before they become eligible to promote to Old generation.

Types of Garbage Collectors:

  • Serial Garbage Collector
  • Parallel Garbage Collector
  • CMS Garbage Collector
  • G1 Garbage Collector


Serial Garbage Collector:
A single thread is used for garbage collection and it will freeze all the application threads while performing GC (Garbage Collection).

Parallel Garbage Collection:
It uses multiple threads for garbage collection, this also freezes all the application threads while performing GC

CMS Garbage Collector:
Concurrent Marksweep Garbage collector, CMS scans the heap mark and mark the instances that requires to be removed and then will clear the marked instances

G1 Garbage Collector:
This will divide the heap memory into equal parts and will perform the GC on the part which has lesser live data.

What is the difference between CMS and G1GC?

Both are designed to minimize long pause when performing GC. But G1GC is used for larger heap that is more than 4GB.

CMS – Uses one or more thread to scan the memory periodically and remove the unused objects, where pause time is minimal but cpu time is more

G1GC – It divides the memory into equal parts and cleans old generation by copy from one part to another.

Read More

Callable and Runnable Examples – ExecutorService

ExecutorService – Callable and Runnable Example
In this article let us see an example using Runnable and Callable tasks using ExecutorService.

Please refer here for Overview of ExecutorService

Runnable Example
Runnable does not return any value and cannot throw checked exceptions

Output:

NOTE:
From the output, we can notice how the executorservice works. We haven’t used Synchronized keyword in any of our methods, but ExecutorService makes sure one thread accesses the methods at a time.

Callable Example
Callable can return Future objects and can throw checked exceptions

Output:

We  have used future object to return string, Future object can return Integer, Boolean etc.
Sample example of using Boolean for the above code,

 

Read More

ExecutorService – An Overview

ExecutorService in Java

What is Executor Service?
Executor service is an interface, which allows us to process tasks asynchronously by threads.

Why ExecutorService over Threads?

ExecutorService has many advantages when compared with using casual threads,

ExecutorService takes care of threads creation for us and also re-uses threads. In java thread creation is expensive as it has to reserve the memory for each threads.  so with ExecutorService, we can create/manage/control life cycle of Threads. Also, ExecutorService provides us with methods like shutdown() and shutdownnow(), When closes the executorservice and will not accept anymore new tasks.

When we use callable in executors, we can get return result for the process.  invokeany() and invokeall() help us to run any or all threads at once.

How to create an ExecutorService?
These are some of the commonly used types of executorservices,

ExecutorService executorService = Executors.newFixedThreadPool(<size>);
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(<size>);
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();

How to create tasks?
We can create tasks that is either Runnable or Callable. Both instances are executed by another thread. So what is the difference between Runnable and Callable tasks?

Runnable

Callable

Runnable doesn’t return a value Callable can return a value
Runnable cannot throw checked exceptions Callable can throw checked exceptions

Once we have implemented the tasks, we use ExecutorService to execute() or submit() the tasks.  What is the difference between execute() and submit()?

execute() – Return type is void
submit() – Returns future object for managing the tasks.

Future Object:

Using Future object we can get the status of callable tasks.  Future.get() method can wait till the callable task is finished and will return the result

invokeAll() – Executes the given tasks, returning a list of Futures holding their status and results when all complete.

invokeAny() – Executes the given tasks, returning the result of one that has completed successfully, without exception.

Shutdown() – Shutdowns the ExecutorService after completing all the submitted tasks and will not accept any new tasks.

ShutdownNow() – Stops all the executing tasks and returns the list of tasks waiting for execution.

We have covered basics of ExecutorService.

 

Read More

Generics in Java with Examples

Generics in Java with Examples

Generics allows us to pass the generic types as parameters to a class or methods.
Example: class A<T>

Generics Advantages:

  • Stronger type checking
  • Casting elimination

Type Parameter Naming Conventions:

  • E – Element
  • K – Key
  • V – Value
  • N – Number
  • T – Type

There are various ways of using Generics, In this post let us see, generics with

  • Upper Bounded Wildcards
  • Unbounded Wildcards
  • Lower Bounded Wildcards

First let us see an example of using generics along with the class

Output:

Now let us see another example of using Generics with Key and Value along with Upper Bound Wildcards, Unbounded Wildcard and Lower Bound Wildcards.

Wildcards usually starts with “?” – Example: List<? extends Number>

Upper Bound Wildcards
Used to relax restrictions on a variable. In the below example we have used upperBound wildcard to pass integers, calculate sum of it and change it double and print it.

Unbounded Wildcards:
Unbounded wildcards is used for unknown types. It can be of any type, Integer or String or object etc..

Lower Bound Wildcards:
Lower Bound Wildcards restricts the unknown type to be specific. (Upper Bound relaxes the restrictions)

 

 

Read More

Bitwise Operators in Java – Right Shift, Left Shift and Unsigned Right Shift

Bitwise Operators in Java – Right Shift, Left Shift and Unsigned Right Shift:
Java Operators are basically divided into six types,

  • Arithmetic Operators
  • Relational Operators
  • Assignment Operators
  • Conditional Operators
  • Logical Operators
  • Bitwise Operators

In this article, We are going to cover Bitwise Operators. We might face some questions in interviews regarding Bitwise operators. So lets us understand what are bitwise operators with examples.

There are 3 types of Bitwise Operators,

  • Left Shift
  • Right Shift
  • Unsigned Right Shift

Before going ahead, Let us understand what these operators do,

Left Shift Operator:

  • Left shift Operator is declared as <<
  • Left shift operator performs the operation of Multiplication
  • The sign of the the integer, Positive or negative impacts the result of left shift operator
  • Example:
    • 2 << 5
    • Output will be 64. (2^0 * 2^1*…2^5)

Right Shift Operator:

  • Right shift operator is declared as >>
  • Right shift operator performs the operation of Division
  • The sign of the integer, Positive or negative impacts the result of Right Shift Operator
  • Example:
    • 2 >> 5
    • Output: 0, (5 is divided by 2)

Unsigned Right Shift Operator:

  • Unsigned Right Shift Operator is declared as >>>
  • Irrespective of sign, It shifts the bits to 0.
  • Example: -14 >>> 2
    • This is include 2 zero’s (>>>2 — we are requesting it to shift 2 bits) to the left, followed by the value

Once we go through the example, We will be able to understand this clearly.

Output:

op1

Now let us see how this output works,

First we are getting the binary value of Both +7 and -7

7 << 2: Left shift is for multiplication,
so,

7^0 = 7
7^1=7
7^2=14
Actual value is 28 and Binary value is 11100 –> Left Shift Operator Output.

Now for the Second Output,
Right Shift Operator is for division,

7 >> 2: Right Shift for Division,

2 Divided by 7, Not divisible so the value is 1. –> Right Shift Operator Output

Now the Unsigned Right Shift Operator,

7 >> 2 and 7>>>2 are always same, except 2 Zero’s are added to the left of the output. 
-7 >>> 2:
Binary value of -7: 11111111111111111111111111111001, Now we shift 2 Zero’s to the left,
Output is,
00111111111111111111111111111110.

If we use, -7>>> 3 (3 zero’s to the left) Output will be,
00011111111111111111111111111111

Read More