Saturday, October 6, 2018

StackOverFlowError: Causes & Solutions


StackOverFlowError is one of the common confronted JVM error. In this blog post lets learn inner mechanics of thread stacks, reasons that can trigger StackOverFlowError and potential solutions to address this error.

To gain deeper understanding in to StackOverFlowError, let's review this simple program:

<<start:code>>
public class SimpleExample {

      public static void main(String args[]) {
           
            a();
      }    

      public static void a() {

            int x = 0;
            b();
      }

      public static void b() {

            Car y = new Car();           
            c();
      }

      public static void c() {

            float z = 0f;
            System.out.println("Hello");
      }
}
<<end:code>>

This program is very simple with following execution code:

1.       main() method is invoked first
2.       main() method invokes a() method. Inside a() method integer variable ‘x’ is initialized to value 0.
3.       a() method in turn invokes b() method. Inside b() method Car object is constructed and assigned to variable ‘y’.
4.       b() method in turn invokes c() method. Inside c() method float variable ‘z’ is initialized to value 0.

Now let’s review what happens behind the scenes when above simple program is executed. Each thread in the application has its own stack. Each stack has multiple stack frames. Thread adds the methods it’s executing, primitive data types, object pointers, return values to its stack frame in the sequence order in which they are executed.




Fig 1: Thread's Stack frame.

Java - Cucumber Hello World example

In the previous article we have seen JBehave Hello World example. In this article we will see same Hello World example but with using Cucumber.

Like JBehave, Cucumber is also used for behavior-driven development (BDD) testing. To know more about Cucumber click here.

Below is the eclipse folder structure -


Wednesday, September 26, 2018

Benefits of call stack tree




Call Stack Tree provides 3 wonderful benefits:
  1. One simplified view
  2. Performance Optimization
  3. Accurate Smoke Test

Let’s discuss them in detail in this article.

1. One simplified view

Thread dumps are the snapshot of all threads running in the application at given moment. Thread dump will have hundreds/thousands of application threads. It would be hard to scroll through every single line of the stack trace in every single thread. Call Stack Tree consolidates all the threads stack trace into one single tree and gives you one single view. It makes the thread dumps navigation much simpler and easier. Below is the sample call stack tree generated by fastThread.io.


                                            Fig 1: Call stack Tree

You can keep drilling down to see code execution path. Fig 2 shows the drilled down version of a particular branch in the Call Stack Tree diagram.


                                            Fig 2: Drilled down Call Stack Tree

Call Stack Tree shows you the class name, method name, and line of the code that has been executed and the number of threads that have executed the line of code.

                                     Fig 3: A single element from Call Stack Tree

From the above element in the Call Stack Tree, you can identify that call() method in buggyCompanyCallable.java is executed by 9 threads.

Saturday, August 25, 2018

Simple spring integration with springboot

In this example we will see a simple file poller application using spring integration. It will poll for a file in a particular location at certain interval and if file is found it will move it to another location.

There are 3 core components of spring integration -

Messages - Messages are the objects sent from one component to another. In our case a file is sent from file poller to file handler.
Channels - Assume channels are the network (a pipe) by which messages are sent from one component to another.
Adapters - Adapters route the output from one channel to the input of another one.



Please see the codes below -



Wednesday, August 15, 2018

Read/Write large excel (xlsx) file

In this article you will see how to write a huge excel file.

Using SXSSFWorkbook you can write large excel file. It is a Streaming version of XSSFWorkbook implementing the "BigGridDemo" strategy. This allows to write very large files without running out of memory as only a configurable portion of the rows are kept in memory at any one time.

Note - I have tested it to write 10,48,576 rows which created 40 MB excel file. If you want to write more rows than this then you may opt to write CSV file.

You need to add below dependencies in your pom.xml

Tuesday, August 7, 2018

Berlin Clock with Java

The Berlin Clock is a rather strange way to show the time. On the top of the clock there is a yellow lamp that blinks on/off every two seconds. The time is calculated by adding rectangular lamps.
The top two rows of lamps are red. These indicate the hours of a day. In the top row there are 4 red lamps. Every lamp represents 5 hours. In the lower row of red lamps every lamp represents 1 hour. So if two lamps of the first row and three of the second row are switched on that indicates 5+5+3=13h or 1 pm.
The two rows of lamps at the bottom count the minutes. The first of these rows has 11 lamps, the second 4. In the first row every lamp represents 5 minutes. In this first row the 3rd, 6th and 9th lamp are red and indicate the first quarter, half and last quarter of an hour. The other lamps are yellow. In the last row with 4 lamps every lamp represents 1 minute.


Sunday, August 5, 2018

JBehave Hello World example (Eclipse + Maven + JUnit)

JBehave is a framework for Behaviour-Driven Development (BDD). To know more about JBehave, click here.

Below is the eclipse folder structure -



Please create a maven project and add the following files -


Monday, July 30, 2018

Binary tree - DFS and BFS

 Depth first search

In depth first search (dfs) you start with a root node and keep on traversing left node (or right node) until you reach leaf node, then backtrack for other side.


There are two ways in which you can implement dfs search -

  • Recursive
  • Iterative using stack


Node.java


Thursday, July 26, 2018

Least Recently Used (LRU) cache

Below java code is a simple implementation of Least Recently Used (LRU) cache using HashMap and LinkedList.

For simplicity i am taking [Integer, String] as a key value pair for the cache, you can use any other structure as per your requirement.

LRU cache requirement -

get(key) will return the value if  present otherwise will return 'NA'

set(key,value) will insert the value if it is not already present else update the value. Also when cache reaches its MAX capacity it should remove least recently used value before inserting a new value.

Logic -
HashMap will contain the key,value pair of the cache and LinkedList will be used to track the usage. As you know LinkedList is a Doubly-linked list implementation of the List which maked insertion and deletion faster. Here first item will be the oldest item whereas last item will be the most recent item.



Data.java



Wednesday, July 25, 2018

Simple junit test case with mockito

Mocking is a way to test the functionality of a class in isolation. Mockito facilitates creating mock objects seamlessly. It uses Java Reflection in order to create mock objects for a given interface. Mock objects are nothing but proxy for actual implementations. To know more about mockito, click here.

Maven dependiencies

This is simple junit testing, we will see integration testing in a different article.

Greeting.java
This is the Greeting.java class for which we are writing junit test cases

GreetingTest.java

Find a pair of elements from an array whose sum equals to a given number

The best way would be to insert every element into a hashset. Then for every x, we can just look up its complement, T-x.
Overall the Time Complexity of this approach is O(n).


Simple block chain code with Java

A blockchain is the structure of data that represents a financial ledger entry, or a record of a transaction. Block chain contains list of blocks, each block will contain transaction and a hashcode of previous block. similarly next block will contain its transaction and hashcode of current block thus if any of the transaction value gets change in blockchain subsequent blocks hashcode will change.



If you dont know about hashcode, The hashcode of a Java Object is simply a number, it is 32-bit signed int, that allows an object to be managed by a hash-based data structure.

Transaction.java - It contains transaction information

Friday, July 13, 2018

Spring boot web application with JSP

In this article we will see a sample spring boot web application with front end as JSP

Maven project structure -

Spring boot web application with thymeleaf


In this article we will see a sample spring boot web application with front end as thymeleaf. To know more about thymeleaf, click here.

Note you can use any other view technology like JSP instead of thymeleaf as per your requirement

Project structure -

Friday, June 15, 2018

Simple Springboot + hibernate + mysql example

This is a simple spring boot + hibernate (JPA) example.

Below are the tables created in MySQL

create table category
(
catid int not null auto_increment,primary key (catid),
catname  varchar(30) not null
);


create table menu
(
menuid int not null auto_increment, primary key (menuid),
menuname varchar(60) not null,
catid int not null, 
        foreign key (catid) references category(catid)

);


Here is the pom.xml file