Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, 14 September 2017

java.lang.OutOfMemoryError: GC overhead limit

Java runtime environment contains a built-in Garbage Collection (GC) process. In many other programming languages, the developers need to manually allocate and free memory regions so that the freed memory can be reused.
Java applications on the other hand only need to allocate memory. Whenever a particular space in memory is no longer used, a separate process called Garbage Collection clears the memory for them. How the GC detects that a particular part of memory is explained in more detail in the Garbage Collection Handbook, but you can trust the GC to do its job well.

The cause

The java.lang.OutOfMemoryError: GC overhead limit exceeded error is the JVM’s way of signalling that your application spends too much time doing garbage collection with too little result. By default the JVM is configured to throw this error if it spends more than 98% of the total time doing GC and when after the GC only less than 2% of the heap is recovered.
The java.lang.OutOfMemoryError: GC overhead limit exceeded error is displayed when your application has exhausted pretty much all the available memory and GC has repeatedly failed to clean it.

Example

In the following class creates a “GC overhead limit exceeded” error by initializing a Map and adding key-value pairs into the map in an unterminated loop:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package com.blogspot.informationtechnologyarchive;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class ExampleGCOverheadLimit {

 public static void main(String[] args) {
  Map<Integer,String> map = new HashMap<Integer,String>();
     Random r = new Random();
     while (true) {
       map.put(r.nextInt(), "value");
     }
 }

}
As you might guess this cannot end well. And, indeed, when you launch the above program with:
java -Xmx100m -XX:+UseParallelGC ExampleGCOverheadLimit
You soon face the java.lang.OutOfMemoryError: GC overhead limit exceeded message.

Solution

As a solution (or rather to consider it as a workaround), if you just wished to get rid of the “java.lang.OutOfMemoryError: GC overhead limit exceeded” message, adding the following to your startup scripts would achieve just that: 
 -XX:-UseGCOverheadLimit

Friday, 25 August 2017

Java - Object creation and Data encapsulation

Object creation

A java class is the definition of a data structure plus actions that operate on them which typically corresponds to a real world object or concept. Constructors are used to initialize the member variables of a class. When an object is created, memory is allocated for the object and the constructor for the class is executed. Constructors are used to initialize an object. Whenever an object is created, a constructor executes. A default constructor is the one that has no arguments and is provided automatically for all classes. This constructor will initialize all instance variables to default values.
Example: the following class use two constructors, the first (line 8) has no parameters while the second (line 13) one has one so you can set the value of name during the object creation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.blogspot.informationtechnologyarchive;

public class Employee {

 private String name;
 
 // Constructor 1 without parameters
 public Employee() {
  this.name = "Jack";
 }
 
 // Constructor 2 with a parameter
 public Employee(String name){
  this.name = name;
 }
 
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

}
Objects are created using the new keyword. The keyword is used in conjunction with a classname and results in memory being allocated from the heap for the object.
Continuing the previous example, we creating two employee objects with both constructors:
1
2
3
4
5
6
 public static void main(String[] args) {
  Employee employee1 = new Employee();
  Employee employee2 = new Employee("Bob");
  System.out.println("Employee 1: " + employee1.getName());
  System.out.println("Employee 2: " + employee2.getName());
 }
The output will be:
Employee 1: Jack
Employee 2: Bob

Data encapsulation

Data encapsulation is concerned with hiding irrelevant information from the programmer and exposing the relevant information. Hiding the implementation details allow changes without affecting other parts of the program.
As example, consider the implementation of the Employee class, the instance variable was declared as private (line 5) and the methods getName and setName were declared as public so you can read and write the name fied but if the metod setName was declared as private then you can only read the name.

Default constructors

A default constructor is normally present for a class. If a class does not have any constructors explicitly declared, it automatically has a default constructor. A default constructor is a constructor that has no arguments.
As example we change Employee class using a default constructor:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package com.blogspot.informationtechnologyarchive;

public class Employee {

 private String name;
 
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

}

Referencing instance variables

A reference variable holds a reference, or pointer, to an object. A field or variable of the object is accessed by following the object reference variable name with a period and then the field or method name. The following code snippet illustrates possible references using the Employee class based upon the declaration of Employee found in the previous section:

1
2
Employee employee = new Employee();
String name = employee.getName();

Thursday, 13 July 2017

Getting started java project with maven

To begin a development of  java project managed with maven, you need two mandatory requirement: the Java Development Kit (JDK) and Apache Maven tool both installed. An onother optional requirement but I think it indispensable the usage of an Integrated Development Environment (IDE) tool as Eclipse. 

Installing JDK

If you don't already installed the JDK than you can install the Oracle JDK available in this web page

Installing Apache Maven

You can refer the official guide available in this web page. If you use an ubuntu OS as the virtual machine created in previous post than you can install the latest maven version using the following commands:
To get all the available Maven package.
$ apt-cache search maven
To install the latest Maven version.
$ sudo apt-get install maven
Check post installation.
$ mvn -v
If the installation is completed with success the output will be similary as:
Apache Maven 3.3.9
Maven home: /usr/share/maven
Java version: 1.8.0_73, vendor: Oracle Corporation
Java home: /home/user/jdk1.8.0_73/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.8.0-58-generic", arch: "amd64", family: "unix"

Create project by maven archetype

A maven archetype is a Maven project templating toolkit and it helps create Maven project templates for developers, and provides they with the means to generate parameterized versions of those project templates. You can use a simple maven archetype to create a new java project using a single maven command. 
Example:
$ mvn archetype:generate -DgroupId=com.blogspot.informationtechnologyarchive \
-DartifactId=first-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
....
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: /home/user/workspace
[INFO] Parameter: package, Value: com.blogspot.informationtechnologyarchive
[INFO] Parameter: groupId, Value: com.blogspot.informationtechnologyarchive
[INFO] Parameter: artifactId, Value: first-app
[INFO] Parameter: packageName, Value: com.blogspot.informationtechnologyarchive
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: /home/user/workspace/first-app
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 15.438 s
[INFO] Finished at: 2017-**********
[INFO] Final Memory: 19M/90M
[INFO] ------------------------------------------------------------------------
If you use a Linux OS you can perform the "tree command" in first-app directory the output will be:
.
├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── com
    │           └── blogspot
    │               └── informationtechnologyarchive
    │                   └── App.java
    └── test
        └── java
            └── com
                └── blogspot
                    └── informationtechnologyarchive
                        └── AppTest.java

11 directories, 3 files
Now to create an executable jar you use the maven command shown below. Maven will create a target directory with the jar called first-app-1.0-SNAPSHOT.jar.
$ mvn package
[INFO] 
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ my-app ---
[INFO] Building jar: /home/user/workspace/first-app/target/first-app-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.299 s
[INFO] Finished at: 2017-******
[INFO] Final Memory: 10M/167M
[INFO] ------------------------------------------------------------------------ 
Finally you can run your jar:
$ java -cp target/first-app-1.0-SNAPSHOT.jar com.blogspot.informationtechnologyarchive.App
The output in this case will be:
 Hello World!

Principal maven goals

To start execute the following command to compile your application sources:
$ mvn compile
The first time maven will need to download all the plugins and related dependencies it needs to fulfill the command. If you execute the command again, Maven will now have what it needs, so it won't need to download anything new and will be able to execute the command much more quickly.
After the successfully compiling now you want to compile and execute some unit tests:
$ mvn test
Maven downloads more dependencies this time. These are the dependencies and plugins necessary for executing the tests. Before compiling and executing the tests Maven compiles the main code. If you want only compile the unit tests:
$ mvn test-compile
Making a JAR:
$ mvn package
Maven creates only jar in target folder.
Now you'll want to install the artifact you've generated (the JAR file) in your local repository (${user.home}/.m2/repository is the default location):
$ mvn install
To remove the target directory with all the build data before starting so that it is fresh:
$ mvn clean
You can concatenate more maven goals, for example:
$ mvn clean install
If you use eclipse IDE, use the following command before importing the maven project:
$ mvn eclipse:eclipse
Similarly if you use IDEA:
$ mvn idea:idea

Eclipse IDE 

Installing Eclipse IDE

All Eclipse versions are available in this web page. I used Eclipse Neon in this post but you can use any version of eclipse for java. 
Eclipse Neon

Eclipse Maven Plugin

All commands such as those shown in the previous paragraph can be executed in eclipse through its plugin. This eclipse plugin is installed in all eclipse distributions for java. 
The use is quite intuitive: select your project, right button, select "Run As" -> "Run Configurations...." as shown in screenshot below.
Eclipse Run Configuration Item.
When the "Run Configuration" windows is loaded, you can configure your maven goal, you can see the following screenshot as example of "mvn clean install".
Maven clean install configuration.

Internal Links

May be of interest to you:

External Links

  1. Oracle JDK download page
  2. Installing Apache maven - official page
  3. Eclipse Download - official page

Welcome

Hello everybody, Welcome in my blog called "Information technology archive". Obviously the topics will be related to Informatio...