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

Atomic Variables in Java

Atomic Variables in Java
In Java, We have a package java.util.concurrent.atomic. Atomic variables are the one which supports multiple operations on a single variable.

Atomic class has get() method, set() method and also compareandset() method.

Let us see some examples of using Atomic Integer, which is from package java.util.concurrent.AtomicInteger.

We are going to see,

get() – Getting the atomic variable value
set() – Setting the atomic variable value
compareAndSet() – Check the atomic variable value and set it to a new value
addAndGet() – This is similar to variable++
getAndAdd() – This is similar to ++variable
getAndIncrement() – This works similar to getAndAdd, But this increment by 1. (++variable)
incrementAndGet() – This works similar to addAndGet. But increments by 1 (variable++)
getAndDecrement() – This is similar to getAndAdd, This decrements value by 1 (–variable)
decrementAndGet() – This is similar to addAndGet, This decrements value by 1 (variable–)

If we want to subtract some value, We can use addAndGet(-value) / getAndAdd(-value)

Now let us see an example of all these above methods,

Output:
op1

Read More

Detecting Internet Connection Using Java

Detecting Internet Connection Using Java
In this article, We are going to see how to check the internet connection using java. We are going to check if the internet is connected or not using Java Code.

We are going to connect to an URL using URL in java and if it gets connected then internet is connected, if not there is no internet connection.

There are various other ways to check internet connection, Here we are going to see 2 ways to check the internet connection.

Method 1:

In this code, We are trying to connect to google.com, if the connection is success – Internet is connected and we will get an output “Internet Connected”, If there is no internet connection, We will get an error message from catch block.

Output:
op1

Method 2:
In Method 2, We are going to use Process from the package java.lang.object

getRuntime() – Returns runtime object associated with the current java application. Most of the methods in runtime are instance methods and invoked with current runtime object. (Java Runtime)

process.waitFor() – Makes the thread wait until the process represented by process object is terminated. This method depends on subprocess too. If the subprocess is terminated it will return immediately, if not the calling thread will be blocked until the subprocess terminates. (Java Process)

The output will be 0(Zero) if the internet is connected and it will be 1(One) if the internet is not connected

Output:
op2

 

Read More

Convert Text to Image using Java

Convert Text to Image using Java
Today, We are going to see how to convert a text into image using Java code. But before we proceed to code, We have to understand some of the classes used in this code.

BufferedImage – The BufferedImage subclass describes an Image with an accessible buffer of image data. This class extends image and implements WritableRenderedImage, Transparency.
BufferedImage Explanation

Font – Font class extends Object and Implements Serializable.  The Font class represents fonts, which are used to render text in a visible way
Font Details

FontMetrics – FontMetrics extends Object and Implements Serializable. The FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a particular screen
FontMetrics Details

RenderingHints – The RenderingHints class defines and manages collections of keys and associated values
RenderingHints Details

Now lets us see an example code – Changing Text into an Image.

Once you run the code,

op1

 

Read More