memory – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Mon, 18 Oct 2021 18:18:43 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 memory – Java2Blog https://java2blog.com 32 32 [Fixed] Initial heap size set to a larger value than the maximum heap size https://java2blog.com/initial-heap-size-set-to-a-larger-value-than-the-maximum-heap-size/?utm_source=rss&utm_medium=rss&utm_campaign=initial-heap-size-set-to-a-larger-value-than-the-maximum-heap-size https://java2blog.com/initial-heap-size-set-to-a-larger-value-than-the-maximum-heap-size/#comments Wed, 30 Dec 2020 09:48:34 +0000 https://java2blog.com/?p=11481 In this post, we will how to resolve initial heap size set to a larger value than the maximum heap size in java.

Problem: Initial heap size set to a larger value than the maximum heap size

This error is related to Xmx and Xms parameters in java and these parameters are used to provide heap memory of the JVM.

-Xms: This specifies initial heap size for JVM
-Xmx: This specifies maximum heap memory size for JVM

This simply means JVM will start with mimimum Xms amount of memory and can take up to xmx amount of memory.

Let’s reproduce this error now.

We will take a simple example about how to print arraylist in java.

package org.arpit.java2blog;

import java.util.ArrayList;

public class PrintArrayListMain {

    public static void main(String[] args) {
        ArrayList countryList=new ArrayList<>();
        countryList.add("India");
        countryList.add("China");
        countryList.add("Bhutan");
        System.out.println(countryList);
    }
}

Let’s compile and run the code.

C:\Users\Arpit\Desktop\javaPrograms>javac PrintArrayListMain.java

C:\Users\Arpit\Desktop\javaPrograms>java -Xms1024m -Xmx512m org/arpit/java2blog/PrintArrayListMain
Error occurred during initialization of VM
Initial heap size set to a larger value than the maximum heap size

As you can see, we got the error Initial heap size set to a larger value than the maximum heap size.

C:\Users\Arpit\Desktop\javaPrograms>java -Xms2g -Xmx1g org/arpit/java2blog/PrintArrayListMain
Error occurred during initialization of VM
Initial heap size set to a larger value than the maximum heap size

Solution 1: Initial heap size set to a larger value than the maximum heap size

We are getting this error because Xms(minimum heap size) is greater than Xmx(maximum heap size).

Xms should always be lesser than Xmx to run java program correctly.

Let’s change -Xms to 512m and -Xmx to 1024m now.

C:\Users\Arpit\Desktop\javaPrograms>java -Xms512m -Xmx1024m org/arpit/java2blog/PrintArrayListMain
[India, China, Bhutan]

As you can see, error is resolved now and we got expected output.

That’s all about initial heap size set to a larger value than the maximum heap size in java.

Solution 2: Change Xms value in vmoptions file for intellij

If you are getting this error in intellij, then you should check Xms value in vmoptions file.

On windows:
You should be able to find the file on windows at following path:

C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2.3\bin

On Mac:
You should be able to find the file on mac at following path:

~/Library/Preferences/IntelliJIdea2019.2/idea64.vmoptions

On linux:
You should be able to find the file on linux at following path:

~/.IntelliJIdea2019.2/config/idea64.vmoptions

You should change version based on your intellij version in above paths.

Check the value of Xms in idea64.vmoptions file and if it is greater than Xmx or not. If it is greater than Xmx, then we should fix it.

Here is content of idea64.exe.vmoptions file.

-server
-Xms128m
-Xmx512m
-XX:ReservedCodeCacheSize=240m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-ea
-XX:CICompilerCount=2
-Dsun.io.useCanonPrefixCache=false
-Djdk.http.auth.tunneling.disabledSchemes=""
-XX:+HeapDumpOnOutOfMemoryError
-XX:-OmitStackTraceInFastThrow
-Djdk.attach.allowAttachSelf=true
-Dkotlinx.coroutines.debug=off
-Djdk.module.illegalAccess.silent=true

That’s all about how to fix Initial heap size set to a larger value than the maximum heap size in java.

]]>
https://java2blog.com/initial-heap-size-set-to-a-larger-value-than-the-maximum-heap-size/feed/ 1
What are Xmx and Xms parameters in java https://java2blog.com/xms-xmx-parameter-java/?utm_source=rss&utm_medium=rss&utm_campaign=xms-xmx-parameter-java https://java2blog.com/xms-xmx-parameter-java/#respond Sun, 15 Sep 2019 17:42:55 +0000 https://java2blog.com/?p=7772 In this post, we will see about Xms and Xmx parameter in java.

-Xmx specifies maximum memory size for Java virtual machine (JVM), while -Xms specifies the initial memory size.

It means JVM will be started with Xms amount of memory and JVM will be able to use maximum of JVM amount of memory.

Let’s understand this with help of example.

java -Xms512m -Xmx1024m

So java process will start with 512 MB of memory heap and can use upto 1024 MB of memory heap.

-Xmx and -Xms can be defined in different size such as kilobytes, megabytes and gigabytes.

-Xmx2048k
-Xmx1024m
-Xmx2g

If Java process exceeds -Xmx memory size, then you will java.lang.OutOfMemoryError.

Default initial size is allocated on the based of ergonomics algorithm.

-Xms and -Xmx are the options for JVM’s heap and JVM can use more memory than size allocated to heap.

If you want to learn about all -X option, you can use java -X command.

Apples-MacBook-Pro-5:~ apple$ java -X-Xbatch
disable background compilation-Xbootclasspath/a:
append to end of bootstrap class path

-Xcheck:jni
perform additional checks for JNI functions

-Xcomp
forces compilation of methods on first invocation

-Xdebug
provided for backward compatibility

-Xdiag
show additional diagnostic messages

-Xfuture
enable strictest checks, anticipating future default

-Xint
interpreted mode execution only

-Xinternalversion
displays more detailed JVM version information than the
-version option

-Xloggc:<file>
log GC status to a file with time stamps

-Xmixed
mixed mode execution (default)

-Xmn<size>
sets the initial and maximum size (in bytes) of the heap
for the young generation (nursery)

-Xms<size>
set initial Java heap size

-Xmx<size>
set maximum Java heap size

-Xnoclassgc
disable class garbage collection

-Xrs
reduce use of OS signals by Java/VM (see documentation)

-Xshare:auto
use shared class data if possible (default)

-Xshare:off
do not attempt to use shared class data

-Xshare:on
require using shared class data, otherwise fail.

-XshowSettings
show all settings and continue

-XshowSettings:all
show all settings and continue

-XshowSettings:locale
show all locale related settings and continue

-XshowSettings:properties
show all property settings and continue

-XshowSettings:vm
show all vm related settings and continue

-XshowSettings:system
(Linux Only) show host system or container configuration and continue

-Xss<size>
set [java thread](https://java2blog.com/java-thread-example/ “java thread”) stack size

-Xverify
sets the mode of the bytecode verifier

–add-reads <module>=<target-module>(,<target-module>)*
updates <module> to read <target-module>, regardless
of module declaration.
<target-module> can be ALL-UNNAMED to read all unnamed
modules.

–add-exports <module>/<package>=<target-module>(,<target-module>)*
updates <module> to export <package> to <target-module>,
regardless of module declaration.
<target-module> can be ALL-UNNAMED to export to all
unnamed modules.

–add-opens <module>/<package>=<target-module>(,<target-module>)*
updates <module> to open <package> to
<target-module>, regardless of module declaration.

–illegal-access=<value>
permit or deny access to members of types in named modules
by code in unnamed modules.
<value> is one of “deny”, “permit”, “warn”, or “debug”
This option will be removed in a future release.

–limit-modules <module name>[,<module name>…]
limit the universe of observable modules

–patch-module <module>=<file>(:<file>)*
override or augment a module with classes and resources
in JAR files or directories.

–disable-@files
disable further argument file expansion

–source <version>
set the version of the source in source-file mode.

These extra options are subject to change without notice.

The following options are Mac OS X specific:
-XstartOnFirstThread
run the main() method on the first (AppKit) thread

-Xdock:name=<application name>
override default application name displayed in dock

-Xdock:icon=<path to icon file>
override default icon displayed in dock

The -X options are non-standard and subject to change without notice.

Please note that it is quite important to set -Xms and -Xmx parameters correctly. Java 13 has introduced a new feature in Z garbage collector where it will uncommit the memory to CPU but it won’t uncommit below -Xms parameter, so if you put -Xms and -Xmx as equal, it will basically disable this feature. This feature is quite useful where memory footprint is a concern.

That’s all about Java’s -Xmx and -Xms parameters.

]]>
https://java2blog.com/xms-xmx-parameter-java/feed/ 0
Garbage Collection in java https://java2blog.com/garbage-collection-java/?utm_source=rss&utm_medium=rss&utm_campaign=garbage-collection-java https://java2blog.com/garbage-collection-java/#comments Tue, 16 Jul 2019 04:47:44 +0000 https://java2blog.com/?p=7476 In this post, we will see about Garbage Collection in java.

I will try to explain with the help of diagrams and examples rather than theory.

JVM Memory is divided into three parts

  • Young generation
  • Old generation
  • Metaspace (Perm Gen)

Young Generation

As the name suggests, young generation is the area where newly created objects are allocated.

  • When young generation fills up, it cause minor garbage collection aka Minor GC.
  • When minor Gcs occurs, dead objects will be removed from young generation.
  • If you have lot of dead objects in young generation, Minor GC will be perfomed faster.
  • All minor GCs are “stop the world” events, so when minor GCs occurs, application threads will also stop.

Let’s understand more about how objects are allocated in Young generation.

Young generation is divided into 3 parts.

  • Eden space
  • Survivor space S0
  • Survivor space S1

Here is illustration of the young and old generation.

YoungOldGeneration

    • All newly created objects are allocated in eden space.
    • When Eden space is completely filled with objects then minor GC will occur. All the objects which are not dead or unreferenced will be moved to one of the survivors spaces. In our case, let’s say all the objects are moved to S0.


S0AllocatedObjects

    • When Eden space is filled again, then all the live objects in Eden space andSurvivor space S0 will be moved to Survivor space S1.

S0T0S1AlloactedObjects
S1AllocatedObjects

  • Once objects are survived multiple cycles of minor GC, they will be moved to old generation. You can control this threshold by MaxTenuringThreshold. The actual tenuring threshold is dynamically adjusted by JVM.

Let’s try to demonstrate this behavior with the help of example:
You have below class in which I am creating short-lived objects for demonstration.

package org.arpit.java2blog;

import java.math.BigDecimal;

public class GCCollectorExample {
    public static void main(String args[])
    {
        createObjects();
    }
    private static void createObjects() {

        long count = 0;

        while(true) { 
            // Creating short-lived objects just for illustration
            BigDecimal shortLivedBigDecimal1 = new BigDecimal(count++);
        }
    }
}

When you run the program. Let’s check memory allocation in Visual GC (A visualVM plugin)

S0AndEdenDemonstation-1024x422

As you can see, we have few objects in S0 and once eden space is completely filled, all referenced objects will be moved to S1.

S1FilledAndEdenDemonstration


Old generation

  • It is used to hold old long surviving objects
  • It is generally larger than the young generation.
  • When tenured space is completely filled(or predefined threshold) with objects then Major GC will occur. It will reclaim the memory and free up space.
  • Often, Major GCs are slower and less frequent than minor GC.

How can you use this information to optimize memory?
It depends on nature of application.
If you have lots of temporary objects then there will be lot of minor gc. You can provide arguments XX:NewRatio=1 to distribute 50% to young generation and 50% to old.
By default, NewRatio=2 hence young Generation is 1/3 of total heap.
Similarly, If you have too many long-lived objects, then you might need to increase size of tenure space by putting high value of NewRatio.

Why two survivor spaces?

You must be wondering why do we have 2 survivor space. We have 2 survivor spaces to avoid memory fragmentation. Each time you copy objects from eden to survivor and you get empty eden space and 1 empty survivor space.


Garbage Collection Algorithms

JVM comes with several algorithms for young and old generation. There are 3 types of algorithms

serial collector

It uses single thread to perform all the garbage collection and is suitable for basic application with single processor machines.

SerialGC

Parallel collector

It uses multiple CPUs to perform garbage collector. While serial collector uses 1 thread to perform GC, parallel GC uses several threads to perform GC and it is useful when there is enough memory and good number of cores.

ParallelGC

Concurrent collector

Concurrent collector performs garbage collection with application threads. It is useful for applications which have medium to large datasets and require quick response time.

concurrentGC

You can use different GC algorithms for young and old generations but you can pair only compatible algorithms.

For example: You can not pair Parallel Scavenge for young generation to Concurrent mark sweep for old as parallel scavenge does not provide synchronization which is required in CMS.

Here are garbage collectors which you can use for young and old generation.
Young CollectorOld CollectorJVM options
Serial (DefNew)Serial Mark-Sweep-Compact-XX:+UseSerialGC
Parallel scavenge (PSYoungGen)Serial Mark-Sweep-Compact (PSOldGen)-XX:+UseParallelGC
Parallel scavenge (PSYoungGen)Parallel Mark-Sweep-Compact (ParOldGen)-XX:+UseParallelOldGC
Serial (DefNew)Concurrent Mark Sweep-XX:+UseConcMarkSweepGC 
-XX:-UseParNewGC
Parallel (ParNew)Concurrent Mark Sweep-XX:+UseConcMarkSweepGC 
-XX:+UseParNewGC
G1-XX:+UseG1GC

There are a lot of changes in garbage collectors after Java 8, I will try to cover them in my next articles.

If you have any suggestions on this article, please comment.

]]>
https://java2blog.com/garbage-collection-java/feed/ 4
Java virtual Machine(JVM) and its architecture https://java2blog.com/java-virtual-machine-architecture/?utm_source=rss&utm_medium=rss&utm_campaign=java-virtual-machine-architecture https://java2blog.com/java-virtual-machine-architecture/#respond Fri, 18 Aug 2017 19:24:52 +0000 http://www.java2blog.com/?p=3407 In this article, you will know about java virtual machine which made Java as more popular.

We all know that Java applications can be write once and run many times anywhere. This is possible with only JVM. Because Java was designed to run on a virtual machine. A virtual machine is software. This JVM will run on any kind of hardware. So it can be run anywhere.

When we compile java program .class file will be generated. JVM will execute .class file which contains byte code. And JVM is responsible for invoking the main method first where the execution will start.
Now we will learn about JVM architecture.

JVM architecture includes the main components which are required to run a program on a machine.

JVM Architecture diagram

Now we will see each part in detail

JVM Architecture

Class Loader

Class loader sub system is responsible for class loading, linking, and initialization.

Loading

here loader will search for the classes and load in order.

It will contain 3 parts:

  1. Bootstrap class loader: It loads classes that are related to java platform and the classes which are in bootstrap path which is present in rt.jar. Actually, rt.jar contains all compiled classes.
  2. Extension class loader: Here the classes which will use Java extension mechanism will be loaded. These classes will reside in extensions directory as .jar files.
  3. Application class loader:  these classes are defined by users. These classes will be found by using class path variable.

After loading object is created for the .class file.It is used to represent memory in heap. And this object is used by the programmer to retrieve information.

Linking

Linking involves verification, preparation, Resolution.

  1. Verification it will verify whether the byte code is properly formatted that means the binary representation of the class has followed the structural constraints or not. If not followed then Verify Error must be thrown. This Error is sub class of LinkageError.
  2. Preparation In this stage static fields creation and initialization will be done. That means allocating memory for static variables and initialization of those. In initialization, only default values will be allocated.
  3. Resolution In this process symbolic references will be dynamically replaced with their direct references (concrete values).

Initialization

In this phase classes and interfaces will be initialized. This will be done by executing the initialization method of the class or interface.

Runtime data areas (memory)

JVM organizes memory in several runtime data areas. For the execution of the program, these data areas are needed. Some memory will be shared among all the threads.

JVM Method area

Now we will see these data areas in detail.

  1. Method area : This is logically a part heap space which will contain the class skeleton. It stores per class structures means run time constants and static variables, methods, constructors, class names and also class type information. It is a shared resource. Only one method area will reside in JVM. In Runtime constant pool string literals will be stored. Here literals don’t relate to any object instances. Run time constant pool doesn’t relate to object instances.
  2. Heap: Here information about objects will be stored. If we create object in heap space will be allocated. If object dies then memory garbage collected. It is common space shared among all threads.
  3. Stack area: It is not shared memory. Per every thread one run time stack will be created. It holds local variables, parameters, intermediate results and other data. It plays role in method invocation and return. JVM stores thread information in discrete frames. These frames will be stored in JVM stacks with push and pop operations. Here stack memory need not to be contiguous and it is dynamically expanded. If memory is not sufficient for expansion it will throw out of memory error.
  4. PC register: whenever new thread is created then it will get pc register. Pc register will store the address of current instruction to be executed.
  5. Native method stacks: native method stack will store native methods. This is also not a shared resource. Native method is java method but implementation will be another language mostly in c. these methods usually used to interface the system calls and libraries.

Execution engine

Execution engine will execute the java byte code that presents in run time data areas. Each byte code instruction contains opcode and operand. With the help of both execution engine will execute. Java Byte code should be changed to machine understandable. It should be done by compiler or interpreter.

Interpreter

It can interpret the byte code instructions line by line. It can interpret faster than compiler. But the repeated code should also be interpreted again. This is only the disadvantage about the interpreter.

JIT compiler(just In time)

it is mainly used for repeated codes. As this is the disadvantage of the interpreter to compensate that disadvantage this compiler came into the picture. The compiler takes more time than interpreter. But here JIT compiler will improve the performance. Actually, every method will be interpreted first. If call count of this method increases more than JIT threshold than that method will be compiled by JIT compiler. JIT compiler will translate byte code into native code. After that only native code will be executed only. That means JIT compiler will be invoked at the appropriate time and operated based on method frequency.

Java Native Interface

Java supports native codes through JNI interface. Native methods are useful for system calls and other issues related to memory management and performance issues. JNI is a framework that will be used to interface the native applications. It will enable java application to call and to be called by native applications.

Native Method Libraries

These native method libraries contain native methods. We will see some uses why we need to use native libraries.

Our system hardware may have some special capabilities. To use those special qualities for our application we need native methods.Some Native methods provide extra speed.
For memory management also some native methods will be designed.Usually, native methods will be written in c or c++.
That’s all about Java Virtual Machine(JVM).

]]>
https://java2blog.com/java-virtual-machine-architecture/feed/ 0