java.lang.OutOfMemoryError: Requested array size exceeds VM limit

Posted on Updated on

java-logo

Java has got a limit on maximum Array size allocation i.e -231 to 231-1 . The exact limit is platform specific.

when your application get crashed and throw java.lang.OutOfMemoryError: Requested array size exceeds VM limit  that means trying to allocate an array which size is larger than VM supports size.

Example here :-

int [] arr = new int[Integer.MAX_VALUE];
or
int [] arr = new int[Integer.MAX_VALUE-1];
output :-

Exception in thread “main” java.lang.OutOfMemoryError: Requested array size exceeds VM limit

Solution :

The java.lang.OutOfMemoryError: Requested array size exceeds VM limit can appear as a result of either of the following situations:

  • Your arrays grow too big and end up having a size between the platform limit and the Integer.MAX_INT
  • You deliberately try to allocate arrays larger than 2^31-1 elements to experiment with the limits.

Initializes array size with Integer.MAX_VALUE-2 to get rid of such errors  : –

int [] arr = new int[Integer.MAX_VALUE-2];

 

see more

Thanks

 

 

 

Advertisements

What is String pool in Java

Posted on Updated on

String pool is an special area of Method Area in JMM( Java Memory Model ) that store String literals and return same reference which contain are already exists in the Pool. Only one Method Area exists per JVM ( Java Virtual Machine ) that is shared among all JVM Threads Object. Method Area is created at time on JVM start-up, Although the method area is logically part of the heap.

A run-time Constants pool is  created per-class or per-interface at runtime representation of constant_table in per class file. Each runtime constant-pool is allocated in Java virtual machine’s Method Area. A runtime constant-pool is created per-class or per-interface at run-time when class or interface is constructed by JVM.

As you know String is a immutable class means every change made on String create a new ( Object ) memory location in Heap.

java-string-pool

When we create a String literals then it first check the contains of String into String Pool if it already exists in the pool then reference of existing String literals will be returned otherwise it put into String pool instead of creating a new String Object.

Following example create only one Object :-

String string1 = "abcd";
String string2 = "abcd";

First String literals “abcd” will be looked up into String Pool if it’s not exist then it will be created an Object in Heap but again second line get executed it first check into String Pool and found String literals “abcd” in pool so rather then creating a new Object of String it returns the existing String reference.

Following are example that will give more idea about String Pool:-

both s1 and s2 String variable point to same reference just because it is internally store into String pool. Although == operator and equals() returns same value i.e true.

String s1 = “jim”;
String s2 = “jim”;

System.out.println(s1==s2); // true.
Object s2 is the same object with s1. But if you create using new operator:
String s1 = “jim”;
String s2 = new String(“jim”);
System.out.println(s1==s2); //false.
It will allocate new Object instead getting from String constant pool.
Another sample:
String s1 = “jim”;
String s2 = “j”+”im”;String s3 = “j”;
String im = “im”;
s3+= im;
System.out.println(s1==s2); //true.System.out.println(s1==s3); //false.
Concatenation during runtime will create new String Object.
Sample if using final modifier:
final String s1 = “j”;
final String s2 = “im”;
String jim = “jim”;
System.out.println(s1+s2 == jim); // returns true: Constant expression.
String s3 = “j”;
String s4 = “im”;
System.out.println(s3 + s4 == jim); // returns false: Not a constant expression.

 

Another important point to keep in mind that intern() in String class which make sure once String get interned then string constant will be added in String pool.

Example here :-

String s1 = "test";
String s2 = new String("test");  // "new String" guarantees a different object

System.out.println(s1 == s2);  // should print "false"

s2 = s2.intern();
System.out.println(s1 == s2);  // should print "true"

Difference between @Component and @Bean in Spring

Posted on Updated on

spring-logo

This is also frequently asked interview question for experience Java interview question. Most of Java developer  get confused to deliver the right answer to interviewer. Though Spring also create a lot of confusion about annotation and manual base configuration and other things but good concept and knowledge are always appreciable.

Here, In this section we will discuss difference between @component (@service,@repository and @controller) and @bean annotation.

First of all @component is a generic annotation and it can be used across the application. In enterprises or multi-layer application it is classified into @service,@repository and @controller for more code readable and understandable.

Technically on multi-layer application has application layer, Service layer,business layer and persistence layer. Subsequently annotations are used to represent it.

Different between @Component and @Bean

@Component, @Service, @Repository and @Controller annotations are used for automatic bean detection using classpath scan in Spring framework. Spring container automatically scan and identify all beans annotated by @Component, @Service, @Repository and @Controller.
Service Layer :-

@Service("userService")
public class UserService {

....

}

Persistence Layer :-

@Repository("userDAO")
public class UserDAO {

....

}

Controller / Presentational Layer :-

@Controller("userController")
public class UserController {

....

}

Root component Package defined in spring configuration xml file then spring container scan and initialized all classes present in the classpath coming under the base-package annotated.

<context:component-scan base-package="com.service" />

@Bean annotation is used to explicitly declare a single bean rather than letting spring container do it automatically. It decouples the declaration of bean from bean definition.


public class AuthenticationService {
	
	private static final Logger logger = Logger.getLogger(AuthenticationService.class);
        ...
        ...
}
@Configuration
public class AppConfig {
@Bean(name="authenticationService")
    public AuthenticationService getAuthenticationService(){
    	return new AuthenticationService();
    }
}

 

More stereotype annotation details as below :- 

  • @Component – generic and can be used across application.
  • @Service – annotate classes at service layer level.
  • @Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
  • @Repository – annotate classes at persistence layer, which will act as database repository.

Disable automatic scan of @Component, @Repository, @Service, @Controller:


<beans>
<context:component-scan use-default-filters = "false" base-package="com.service" /> 
</beans>

 

Arithmetic Operation Using AngularJS

Posted on Updated on

angularjs

Another simple example to calculate Arithmetic operation like +,-,*,/,% operator between two operands.


<!DOCTYPE html >
<html ng-app="dashboard">
<head>
<title>AngularJS</title>
<script type="text/javascript" src="./js/angular.min.js"></script>
</head>
<body ng-controller="myController">
<h1>Welcome to AngularJS Example2</h1>
<table border='1'>
<tr>
<td colspan='2'>
<h2>Arithmetic Operation</h2>
</td>
</tr>
<tr>
<td>Enter First Operand</td>
<td><input type="number" ng-model="number1"></td>
</tr>
<tr>
<td>Enter Second Operand</td>
<td><input type="number" ng-model="number2"></td>
</tr>
<tr>
<td>Select Operator</td>
<td><select ng-model="operation"
ng-options="item for item in operations">
</select></td>
</tr>
<tr>
<td>Result is</td>
<td>{{result}}</td>
<tr>
<td><input type="button" ng-click="AddMe()" value="Result"></td>
</tr>
<table>
</body>

<script>
var dashboard = angular.module("dashboard", []);

dashboard.controller('myController', function($scope) {

$scope.operations = [ '+', '-', '*', '/', '%' ];
$scope.AddMe = function() {

var num1 = $scope.number1;
var num2 = $scope.number2;
switch ($scope.operation) {
case '+':
$scope.result = parseInt(num1) + parseInt(num2);
break;
case '-':
$scope.result = parseInt(num1) - parseInt(num2);
break;
case '*':
$scope.result = parseInt(num1) * parseInt(num2);
break;
case '/':
$scope.result = parseInt(num1) / parseInt(num2);
break;
case '%':
$scope.result = parseInt(num1) % parseInt(num2);
break;
default:
$scope.message = "Invalid Selection ";
break;

}
};

});
</script>

</html>

Output here :-

angular-exm-002

Simple Add Operation using AngularJS

Posted on

angularjs

Below are very simple example of AngularJS that Add two number. As discussed in “Introduction of AngularJS“, It’s  a powerful Javascript framework that is used to build a rich and dynamic web application.

In this example, we will see how to implement add operation using AngularJS. However, It is easy to write same program in Javascript or other client script language but it would be little bits hard for start-up to write using AngularJS. Here we will discuss code.

ng-app : Specify an AngularJS module to be used as the root module for the application.

Specify module name “dashboard” on root elements.

<html ng-app="dashboard">

Create an object of module “dashboard”.

var dashboard = angular.module("dashboard", []);

ng-controller : The ngController directive specifies a Controller class; the class contains business logic behind the application to decorate the scope with functions and values.

Here, module has controller component in AngularJS so create a Controller using controller name and callback function…

AddMe() is defined in button  inside ng-controller “myController” so it’s implementation would be under Controller block.

dashboard.controller('myController', function($scope) {
$scope.AddMe = function() {

var num1 = $scope.number1;
var num2 = $scope.number2;

$scope.result = parseInt(num1) + parseInt(num2);
};

ng-model :- Binding the view into the model, which other directives such as input, textarea or select require.
<input type="number" ng-model="number1">

Download AngularJS Framework from angularjs.org on your file system.

  1. Create a folder on your file system like AngularJSExample1
  2. Download AngularJS Framework and put “angular.min.js” under AngularJSExample1/js/
  3. Create a index.html file under root directory AngularJSExample1.
  4. Copy and paste below html code into index.html
  5. Save and run into browser…

 


<!DOCTYPE html >
<html ng-app="dashboard">
<head>
<title>AngularJS</title>
<!--<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script> -->

<script type="text/javascript" src="./js/angular.min.js"></script>
</head>
<body ng-controller="myController">
<h1>Welcome to AngularJS</h1>
<table border='1'>
<tr>
<td colspan='2'>
<h2>Arithmetic Operation</h2>
</td>
</tr>
<tr>
<td>Enter First Operand</td>
<td><input type="number" ng-model="number1"></td>
</tr>
<tr>
<td>Enter Second Operand</td>
<td><input type="number" ng-model="number2"></td>
</tr>
<tr>
<td>Result is</td>
<td>{{result}}</td>
<tr>
<td><input type="button" ng-click="AddMe()" value="Result"></td>
</tr>
<table>
</body>

<script>
var dashboard = angular.module("dashboard", []);

dashboard.controller('myController', function($scope) {
$scope.AddMe = function() {

var num1 = $scope.number1;
var num2 = $scope.number2;

$scope.result = parseInt(num1) + parseInt(num2);
};
});
</script>

</html>

Output here : –

angular-exm-001

Introduction of AngularJS

Posted on Updated on

angularjs

What is AngularJS ?

AngularJS is a powerful and structural JavaScript framework which is easier to implement in single web applications and allows organizing large, client heavy applications into something manageable. It is an open source web application framework, free and used by thousands of developers around the world.

AngularJS is based on the MVC(Model View Control) pattern that is intended to build rich internet web applications and simplify both development and testing of applications by using MVC architecture and separating your rich internet applications into models, views and controllers. AngularJS creates single page applications, which means the browser is going to load a single page regardless of the size of your application.

AngularJS was developed by Miskohevery and Adam Abron, maintained by Google; used internally by them and MIT. It is licensed under the Apache License version 2.0. It was initially released in 2009 and the current stable release is 1.3.x (Decemeber 1, 2014).

 

AngularJS: In this section, let us summarize the basics of AngularJS.

  • Is a library written in JavaScript
  • Is not a platform or language
  • Is not a plug-in or extension
  • It extends HTML, CSS and JavaScript
  • Is not a DOM manipulation library like jQuery
  • Does not require jQuery or inheritance
  • Does not require one-way data binding and boilerplate code

Why AngularJS?

  • It is based on MVC design pattern which provides numerous ways to build web application at client side.
  • It helps to build client side applications with less code and more flexibility.
  • It extends HTML by using functionality of directives, attributes, expressions and templates to HTML.
  • AngularJS is a MVC architecture which simplifies the development and testing of applications easily for client side.
  • It is good for developing single page applications and front ends for web based applications.
  • It has flexible framework and versatile features. So it is used for both large app projects and small little applications.

Features:

AngularJS (JavaScript based framework) creates applications in a faster way by using several features such as:

  • It is a client side technology which provides powerful things to create dynamic web applications.
  • It is a MVC based framework, allows users to build proper architecture and maintainable web applications.
  • It is an open source web application framework used by thousands of developers around the world.
  • It allows use of reusable components and code reuse.
  • It makes creation of user interface (UI) easy through data binding process.
  • Declarative HTML approach.
  • It helps to divide your application into smaller parts.

Architectural Diagram and Components: Let us have a look at the architecture diagram of the AngularJS framework and its components.

angular-js-architecture

AngularJS contains modules which act as a container for different types of applications such as controllers, views, directives, factory etc. Module specifies how an application should be bootstrapped. Using modules, processes will be easier to understand; you can reuse the code, end to end tests uses modules to override the configuration etc. It is the place for creating, registering and retrieving angular modules.

Config component only accepts providers from modules, means every service, factory etc are instances of provider. It provides all these instances to routes.

The Routes are used for linking URL’s to controllers and views.

The Views are used to add sophisticated handling of user events. It uses ng-view directive that complements route service by template of the current route to the main layout (index.html) file.

The controller controls the data of AngularJS applications which are regular JavaScript objects. AngularJS defines ng-controller directive which creates new controller objects by using controller function. And new child is available to the controller function as $scope as shown in the diagram.

The views sends element or attribute to the directives which tells AngularJS’s HTML compiler to attach specific behavior to the DOM element and its children.

The factory is used to define the AngularJS service and it is called when a service needs to be instantiated.

Getting Started with AngularJS:

AngularJS is easy to start with. It provides features like two way data binding which makes custom tags, attributes which encapsulate built-in directives that make extending functionality of HTML easier.

  • It is distributed JavaScript file and can be used in a webpage by including AngularJS library as shown below:

<script src=”http:// ajax.googleapis.com/ajax/libs/ angularjs /1.2.26/ angular.min.js”>

</script>

You can also check the latest version of AngularJS on their official website.

  • You can create AngularJS application as shown below:

<htmlng-app></html>

Or

<html ng-app=”MyApp”></html>

Or

<divng-app></div>

Or

<div ng-app=”MyApp”></div>

 

The ng-app attribute is the root element of the AngularJS app.

  • Controller can be defined as shown below:

<div ng-app=” “ ng-controller=”MyController”>

<input type=”text” ng-model=”message”>

</div>

The ng-controller directive defines the application controller. The ng-model directive binds the value of HTML controls such as input fields, select etc to the application data.

  • Implement the controller by using $scope object as written below:

functionMyController($scope){

$scope.message=”Enter your name”;

}

The $scope object refers to the application model which invokes the controller that creates messageproperty in the scope.

Core Concepts: In this section we will have a detailed discussion about the core components and the concepts behind them.

  • Modules
  • Directives
  • Scope
  • Controllers
  • Expressions
  • Templates
  • Routing
  • Filters

Modules:

Modules provide excellent mechanism for dividing the application into small reusable components and specify how an application should be bootstrapped. Modules specify how you define the components in the application and makes application more readable. Each module is identified by a unique name.

Directives:

Directives are core building blocks of AngularJS which are used to create custom HTML tags and can be placed in element names, attributes and comments. Directives can be used as HTML directives which build complex widgets with layered functionality.

Scope:

Scope is an object that binds a view to the controller. In MVC structure, it refers to the application model. Scopes can watch expressions and propagate events as they are arranged in hierarchical structure.

Controllers:

Controllers are JavaScript objects that defines the actual behavior of your app. It is responsible for setting model properties and functions by using $scope object. The controller does not store state and does not interact with remote services.

Expressions:

Expressions are written inside curly braces “{{   }}” denote bindings which referrers to our application model. Expressions do not support control flow statements. AngularJS will output the data where they are used.

Templates:

Template is just old-plain-HTML that does not include any angular specific file templates. It comes with a set of live templates to create controllers etc by using template engine. Templates are used to show information from the model and controller.

Routing:

It is used for linking URL’s to controller and views. Routing is taken care by service providers called$routeProvider to handle routing which is the provider of the $route service. In other words, it’s loading of sub templates depending upon the URL of the page.

Filters:

Filters are used with expressions to transform or modify the data from the models. We can add expressions or directives using pipe character. AngularJS has some of the commonly used filters such as:

  • currency: converts number to currency format.
  • uppercase: converts strings to uppercase.
  • lowercase: converts strings to lowercase.
  • filter: selects subset of items from array.
  • orderBy: orders array by the expression such as ordered alphabetically for strings and numerically for numbers.

Example:

Let’s create one simple example using AngularJS library and create a HTML file as FirstExample.html as shown below:

Listing1: Simple AngularJS application


<!DOCTYPE html>

<html>

<head>

<script src= “http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js”></script>

</head>

<body>

<div ng-app=”” ng-controller=”MyController”>

Enter Name: <input type=”text” ng-model=”userName”><br><br>

Full Name: {{userName}}

</div>

<script>

functionMyController($scope) {

$scope.userName = “David”;

}

</script>

</body>

</html>

As discussed, we have included AngularJS JavaScript file in the HTML page which is defined within the <head> tag. The next part contains AngularJS app which is defined using the ng-app attribute runs inside the <div> tag.

The ng-controller directive defines the application controller. The AngularJS will invoke the “MyControllerwith $scope object which creates property called “usernamein the scope.

Define the model name using ng-model directive defined in the <input> tag. It binds the input field to the controller property “username”.

 

Example here :-

  1. Add two number using AngularJS
  2. Arithmetic Operation using AngularJS.

 

Spring Transaction isolation level

Posted on Updated on

Spring 3 In this discussion, we will see how Spring provided DBMS Transaction Isolation. Here we will elaborate one by one about transaction and it attributes.

Transaction : – It is a sequence of operations ( like read,update and write ) that works as a unit to accomplish a task. like Booking a ticket,Selling a item.

Isolation Level :-  Transaction specify isolation level that defines the degree to which one transaction must be isolated from other resource or data modification by other transaction. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction

Choosing the transaction isolation level does not affect on lock that are acquired to protect the data modification But it’s control the data modification by more than one transaction by define good Isolation level. A low Isolation may be increased the ability of users to access the data at the same time that increase the number of concurrency i.e dirty read or lost of data. conversely higher Isolation level  reduces the type of concurrency effect that user may encounter.

A valid Transaction has four properties that is known as ACID.

  1. Atomicity: It says either all operation get successful or roll-back completely means if any of transaction fails then entire transaction fails.
  2. Consistency: Database remains consistent ( one valid state to other ) after every transaction.
  3. Isolation: Each instance of Transaction work separately in concurrent execution. No two or more transaction instance can be interference or visible to each other.
  4. Durability: Once the transaction is committed then it must be written permanently into Database even if power failure or system failure.

Every RDBMS supports ACID properties like Oracle,MySQL,Microsoft SQL Server,PostgreSQL or more and concept is remains same thought-out technologies.

Transaction isolation is a concept in Spring Framework that applied to Transaction and related with ACID properties.  Isolation level determined how a transaction to be visible to other transaction in concurrent execution. Lower level Isolation increase concurrency effect ( like dirty read and lost of updation) . However higher level Isolation type reduce the concurrency effect that user may encounter.

Hence,Isolation Lavel says, Changes made by one transaction on table data must be visible correctness to other transaction and data must not be dirty or corrupted. 

Isolation Level :- 

  1. Read Uncommitted
  2. Read Committed
  3. Repeatable Read
  4. Serializable

Example : –

In Spring, @Transactional annotation is use to define a Isolation level in your business layer. This mean given method execute under transaction Isolation level.


@Autowired
private UserDAO userDAO;

@Transactional(isolation=Isolation.READ_COMMITTED)
public void signUp(User user) {

  // Interact with userDAO

}

here, we have defined a signUp() to be executed in a Transaction under Isolation level READ_COMMITED.

The following table shows the concurrency side effects allowed by the different isolation levels.

Isolation Level Dirty Read Non Repeatable Read Phantom
Read uncommitted Yes Yes Yes
Read committed No Yes Yes
Repeatable read No No Yes
Snapshot No No No
Serializable No No No
  • Read committed (Database Engine default level)

Read Uncommitted

It is also called a dirty read, Occurs when a transaction allow to read a data from Database which has been modified by other running transaction and not yet committed.

Example : suppose transaction t1 fetched a row a =10 and transaction t2 update to 20 i.e a =20 again transaction t1 fetched same data which return a =20 and then transaction t2 rollback it changes then value a become 10 but still t1 can see a = 20;

Non-repeatable reads

It will happened when one transaction retrieve a row twice then fetched row value get different.

Example :-  suppose Transaction T1 fired a query (“select * from employee where id=1”)

then Second Transaction T2 updated the row values and committed.

Again T1 fired the same query then value would be different.

 

Phantom reads

A phantom read occurs when, in the course of a transaction, two identical queries are executed, and the collection of rows returned by the second query is different from the first.