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.

Advertisements

Foreach vs iterator in Java

Posted on Updated on

6db3a-download Most of you are familiar with these two words. Primarily uses of  for-each is iterator over Array but it’s also used to iterator over Collections. While Iterator() method of Iterable interface  is used to iterator over Collection classes.

In Java Collection Interface, it extends to Iterable Interface which contains an Iterator() method that produced an Iterator. So we can say that all Collection classes has a Iterator() to move throughout a sequences or a collection. Since Map Interface  is not a part of Collection  so Iterator() method is not available in Map but keySet() or values() of Map Interface returns a Collection which is subsequently implemented Iterable Interface.

For-each Example here


import java.util.*;
public class ForEachCollections {
	public static void main(String[] args) {
		Collection cs = new LinkedList();
		Collections.addAll(cs, "Take the long way home".split(" "));
		for (String s : cs)
			System.out.print("‘" + s + "‘ ");
	}
} /* Output:
‘Take’ ‘the’ ‘long’ ‘way’ ‘home’ */

Since cs is a Collection, this code shows that working with foreach is a characteristic of all Collection objects.

The reason that this works is that Java SE5 introduced a new interface called Iterable which contains an iterator( ) method to produce an Iterator, and the Iterable interface is what foreach uses to move through a sequence. So if you create any class that implements Iterable, you can use it in a foreach statement:


import java.util.*;
class IterableClass implements Iterable {
	protected String[] words = ("And that is how "
			+ "we know the Earth to be banana-shaped.").split(" ");

	public Iterator iterator() {
		return new Iterator() {
			private int index = 0;

			public boolean hasNext() {
				return index < words.length;
			}

			public String next() {
				return words[index++];
			}

			public void remove() { // Not implemented
				throw new UnsupportedOperationException();
			}
		};
	}

	public static void main(String[] args) {
		for (String s : new IterableClass())
			System.out.print(s + " ");
	}
} /* /* Output:
And that is how we know the Earth to be banana-shaped.  */

The iterator( ) method returns an instance of an anonymous inner implementation of
Iterator which delivers each word in the array. In main( ), you can see that
Iterable Class does indeed work in a foreach statement.

In Java SE5, a number of classes have been made Iterable, primarily all Collection classes
(but not Maps). For example, this code displays all the operating system environment
variables:


import java.util.*;
class EnvironmentVariables {
	public static void main(String[] args) {
		for (Map.Entry entry : System.getenv().entrySet()) {
			System.out.println(entry.getKey() + ": " + entry.getValue());
		}
	}
}

System.getenv( )7
returns a Map, entrySet( ) produces a Set of Map.Entry elements,
and a Set is Iterable so it can be used in a foreach loop.

A foreach statement works with an array or anything Iterable, but that doesn’t mean that an
array is automatically an Iterable, nor is there any autoboxing that takes place


class ArrayIsNotIterable {
	static  void test(Iterable ib) {
		for (T t : ib)
			System.out.print(t + " ");
	}

	public static void main(String[] args) {
		test(Arrays.asList(1, 2, 3));
		String[] strings = { "A", "B", "C" };
		// An array works in foreach, but it’s not Iterable:
		// ! test(strings);
		// You must explicitly convert it to an Iterable:
		test(Arrays.asList(strings));
	}
}
/* /* Output:
1 2 3 A B C   */

Trying to pass an array as an Iterable argument fails. There is no automatic conversion to
an Iterable; you must do it by hand.

 

Thanks, Please post your comments.

What is difference between (| and || ) and ( & and && ) in Java.

Posted on Updated on

6db3a-downloadThe operators || and && are called conditional operators, while | and & are called bitwise operators. They serve different purposes.
Conditional operators works only with expressions that statically evaluate to boolean on both left and right side.
Bitwise operators works with any numeric operands.
If you want to perform a logical comparison, you should use conditional operators, since you will add some kind of type safety to your code.

a | b: evaluate b in any case

a || b: evaluate b only if a evaluates to false

| is the binary or operator
|| is the logic or operator

Below are some conclusion here :

the operand of every expression is evaluated before the operation is performed except for the short-circuit operators (&&, ¦¦) and ternary operator
behaviour can produce unexpected results if you’re not careful. For example, the following code illustrates what can occur if you try to set the value of a variable in an if condition and you always expect the new value to be available:

int i = 10;
int j = 12;

if( (i<j) ¦ (i=3) > 5 ) // value of i after oper: 3
if( (i<j) ¦¦ (i=3) > 5 ) // value of i after oper: 10

if( (i>j) & (i=3) > 5 ) // value of i after oper: 3
if( (i>j) && (i=3) > 5 ) // value of i after oper: 10

  • with & and ¦ both operands are always evaluated.
  • with && and ¦¦ the second operand is only evaluated when it is necessary.
  • with ¦¦ (i<j) evaluates to true; there is no need to check the other operand as ¦¦ returns true if either of the operands are true.
  • with && (i>j) evaluates to false; there is no need to check the other operand as && returns true only if both operands are true. In this case one is false so there is no need to check the other operand

What is Defensive Copying , Shallow Copy and Deep Copy ?

Posted on Updated on

Defensive copying is concerned with protecting mutable objects e.g. objects who’s state can be modified by the user. If you were pass back the reference of an object any changes a user made to that copy of the object would effect your object because you are only passes a reference to the object and not the actual object itself. This is known as a shallow copy.
To avoid users being able to change the values of your object you can pass back a defensive copy. This means that instead of passing back a reference to your object it passes back a new object but with the same values. This means that any changes the user makes to that copy of the object doesn’t change the value/state of your object.
It’s an interesting idea but I can’t think of a use for this at the moment but I’m sure one day this will come in useful.

Before knowing about Shallow Copy and Deep Copy you need to know about Clonable interface.

Clonable interface –
Java has a clonable interface for make clone of any object.
Clonable Interface is a marker interface.
Clonable Interface has no method.
Class which implements Clonable interface, JVM give the permission for making the clone of         this class.

Shallow Copy –  
Clone can be archived by object.clone() method. It gives the Shallow copy of the object. In this process a new object is created That have all the value and instance variable. And if main object has any references to other object then the references are copied in the shallow copy.

Example – 


class A implements Cloneable{
    
    A(String personName, Integer age){
        this.personName=personName;
        this.age=age;
    }
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    private String personName = null;
    private transient Integer age = null;
    
    public Integer getAge() {
        return age;
    }
    public String getPersonName() {
        return personName;
    }
}

public class Test{
    public static void main(String[] args) throws CloneNotSupportedException {
        A a = new A("Albar", new Integer(50));
        A a1 = (A)a.clone();
        System.out.println(a1.getPersonName());
    }
}

Deep Copy:- 
Deep Copy of any object can be achieved by write the object into byte stream and again deserialize it. It gives the Deep Copy of the object. Deep copy is a totally duplicate copy of an object.
And if main object has any references to other object then the complete new copies of those objects will be available  in the Deep Copy.

Example to get Deep Copy – 


class A implements Serializable{
    
    A(String personName, Integer age){
        this.personName=personName;
        this.age=age;
    }
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    private String personName = null;
    private transient Integer age = null;
    
    public Integer getAge() {
        return age;
    }
    public String getPersonName() {
        return personName;
    }
}


public class Test{
    public static void main(String[] args) throws CloneNotSupportedException {
        try {
            A a = new A("Albar", new Integer(50));
            A deepCopy = null;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            ObjectOutputStream out = new ObjectOutputStream(bos);

            out.writeObject(a);
            out.flush();
            out.close();

            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
            Object obj = in.readObject();
            deepCopy = (A)obj;
            System.out.println(deepCopy.getPersonName());
            }
            catch(IOException e) {
                e.printStackTrace();
            }
            catch(ClassNotFoundException cnfe) {
                cnfe.printStackTrace();
            }
            } 
}

What is Static and Dynamic binding in Java

Posted on Updated on

java-logo It is important to get to know the concept of earlier binding and late binding ( static and dynamic binding ) for every level of Java guys, Also it became a popular interview question which make confuse during interview but good concept always appreciable.

In this section we will explain with good example of how to achieved these two concept and how Java recognized binding is Static or Dynamic.

Most of Java guys says, binding is held at compile time is call earlier binding or static binding like method overloading and binding is held at run time is call dynamic binding like method overriding. Which is enough to make sense for interviewer but If interviewer screw this concept on practical ways and asked you to give  correct output of given code snippet then real confusion get started.

Key Points:-

  • earlier binding is also called as static binding and dynamic binding is also called as run-time binding.
  • method overloading is used to achieved static binding while method overriding is used to achieved dynamic binding.
  • Compiler checks Object Type to achieved Static binding but Dynamic binding used object reference at run-time to call corresponding override method in a Class.
  • Dynamic binding is slower than Static binding because at run time it takes  extra time to find out which method to be called. like C++ virtual table.
  • A method to be called method overload when method name same but number of parameters or type of parameter must be different but A method is called method override when method name is same as well parameter.
  • static or final or private method can be overload but it can’t override.
  • Using return type method overloading can’t be achieved but using covariant return type method override could be achieved. similarly covariant throws exception type.
  • Method overload happened within a class but Method override happened at sub-classes.

 

As below given snippet code need to be considered the binding type and it’s Output.

Compile-time binding example:-


public class CheckBindingType {

	public void print(Object obj) {
		System.out.println(" Print Object");
	}

	public void print(String str) {
		System.out.println(" Print String");
	}

	public static void main(String args[]) {
		Object obj = new String("Hello,This is String Initilization");
		CheckBindingType type = new CheckBindingType();
		type.print(obj);

               type.print(null); 
// Output : "Print String" because the JVM will search for the method from the most specific type to least specific type. 
} } 

In this above code, It is compile time binding. Here, object of CheckBindingType Class call print(obj) method, then Compiler will check the type of “obj”  which is Object Type  and then it look for  print(Object) method and bind the call to this method. hence result will be “Print Object”.

Dynamic binding example:-


class Shape{
	public void draw(){
		System.out.println(" Shape Draw");
	}
}
class Circle extends Shape{
	public void draw(){ // This is method override here
		System.out.println(" Circle Draw");
	}
	
	public void draw(int x){ // This is method overloading
		System.out.println( " Circle Draw at "+x);
	}
}

public class CheckBindingType {

	public static void main(String args[]) {
		Shape shape0 = new Circle();
		shape0.draw();  //  Circle Draw
		
		Shape shape1 = new Shape();
		shape1.draw(); //  Shape Draw
		
		Circle circle1 = new Circle();
		circle1.draw(); // Circle Draw
		circle1.draw(10); // Circle Draw at 10
		
		//Circle circle2 = new Shape(); 
                // Compile time exception, SubType cann't allow to hold the reference of Parent Type.

	}
}


Output :-

Circle Draw
Shape Draw
Circle Draw
Circle Draw at 10

In this below code snippet, It’s Dynamic binding which occurs at run-time. In example, Shape class has a Overridden method “draw()” which overrides into respective sub-class Circle having one additional method “draw(int)”  that’s overloading in this class.

In main class CheckBindingType, draw() method is being called by object i.e Shape or Circle. At run time Java check object reference type if object referenced type is Shape then it call Shape’s draw(), if object hold reference of Circle then it call Circle’s draw().

Hence, first case Shape Type hold reference of sub-class Circle then draw() of sub-class will be called. similarly 2nd and 3rd case, Shape’s draw() and Circle’s draw()  will be called.

 

Fail-fast vs Fail-safe Iterator

Posted on

fail-fast vs fail-safe

 

Since Jdk1.5, It’s becoming a popular interview question today, reason is it touches a bit concurrent package and interviewer can ask more about concurrent package like have you ever used concurrent package in your project if yes then “what concurrent package did you use, explain it.” . This is up to you how to answer those question otherwise say “No”.

In this article, we will discuss how “fail-fast and fail-safe iterator” implemented in Java and it advantage.

fail-fast Iterator occurred when structure of Collection has been modified by one or more Thread during iteration process. Thus in the face of Concurrent modification failed and throw ConcurrentModificationException.

Suppose, we have a Set of Object, In the way One Thread try to iterate over the collection using iterator() and meanwhile structure of collection has been changed by adding,removing or updating element at a same time, Since java.util.Iterator doesn’t support concurrent modification so it will throw an exception.

CheckFailFast.java


import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class CheckFailFast {

	public static void main(String args[]) {
		Set setOfName = new HashSet();
		setOfName.add("Ajay");
		setOfName.add("Santosh");
		setOfName.add("Wasim");
		setOfName.add("Amit");

		Iterator it = setOfName.iterator();
		while (it.hasNext()) {
			String key = it.next();
			if (key.equals("Santosh")) {
				setOfName.remove(key);
			} else {
				System.out.println(" Name is " + key);
			}
		}

	}
}

Output here :-

Exception in thread “main” java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
at CheckFailFast.main(CheckFailFast.java:16)

fail-safe Iterator never throw Exception during iteration process, just because fail-safe works on clone of collection rather than original collection that’s why it is called fail-safe iterator.

Iterator of ConcurrentHashMap keySet is also fail-safe and never throw “java.util.ConcurrentModificationException

CheckFailSafe


import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class CheckFailSafe {
	public static void main(String args[]) {
		Map<String,String> map = new ConcurrentHashMap<String,String>();
		map.put("Ajay","Ajay");
		map.put("Santosh","Santosh");
		map.put("Wasim","Wasim");
		map.put("Amit","Amit");

		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next();
			if (key.equals("Santosh")) {
				map.remove(key);
			} else {
				System.out.println(" Name is " + key);
			}
		}

	}
}

Output here :-

Name is Wasim
Name is Amit
Name is Ajay

Why Java ?

Posted on Updated on

Why Java

 

Today Java became a fundamental programming language that is used to develop application,web ,plugin and mobile application. Simple reason is cross platform,multi-threading capability,object oriented,security,robustness,distributed programming and more.

Why Java ?

We are quite sure that you have heard of Java programming language but there are also many programming language as well such that python,Ruby and C++ to name few. However Java is still one of favorite choice for developer for many reasons. As of date, Java is one of most secure programming language that is used in most of Banking domain and other security base application due to security in nature. Java use own ‘sandbox’ to run untrusted code obtained from open Network.

In addition to that, many enterprise solutions also make use of Java due to the possible types of integrations associated with it. For example, through Java, it is possible to integrate the
application or product with various web services such as payment gateways, crud applications as well as health domain applications. Suffice to say that the possibility through Java can easily be endless but it doesn’t mean that everything should be developed with Java.

Java has been the solution to various platforms that are both developing and stable. In fact, there are many noteworthy companies and projects that use Java for their day-to-day jobs. Some of the ones that you might have heard include Google Maps, Blu-ray discs, Kindle and a few other devices. In addition to that, laptops, supercomputers, and cell phones are also supported by Java making it a very versatile language as compared with others.

In statistical terms, there are roughly 1.1 billion desktops that run Java, 3 billion smartphones running Java, 1.4 billion Java Cards manufactured and is also being used in GPS systems, parking payment stations, lottery terminals, ATMs and many more. That is the power of Java not found in any other platform in the market.

Following are some Java development technologies, tools, and frameworks used to design complex architectures and built applications:

  • Struts, Spring, Hibernate and JPA
  • JAXB and Apache Axis 2/Java
  • JSP, Servlets, JDBC, EJB, JMS, JTA and JUnit
  • Apache Tomcat, JBoss and GlassFish
  • JavaScript, JSF, GWT,AngularJS and jQuery
  • Eclipse, Netbeans and JBoss tools
  • TestNG
  • jBPM and Drools
  • JCR

Why do Programmer choose Java ?

In short, Java is a solution to build a stable, reliable and secure application that run on cross-platform due to platform independent nature. It’s fast and high the performance of application due to atomically handle garbage collector i.e robustness. In fact today most of web site wouldn’t run unless your install JDK in your machine.

Key feature of Java :-

Simple
  • Looks familiar to existing programmers: related to C and C++:
  • Omits many rarely used, poorly understood, confusing features of C++, like operator overloading, multiple inheritance, automatic coercions, etc.
  • Contains no goto statement, but break and continue
  • Has no header files and eliminated C preprocessor
  • Eliminates much redundancy (e.g. no structs, unions, or functions)
  • has no pointers

Added features to simplify:

  • Garbage collection, so the programmer won’t have to worry about storage management, which leads to fewer bugs.
  • A rich predefined class library
Object-Oriented

Java is an object-oriented language, which means that you focus on the data in your application and methods that manipulate that data, rather than thinking strictly in terms of procedures.
In an object-oriented system, a class is a collection of data and methods that operate on that data. Taken together, the data and methods describe the state and behavior of an object. Classes are arranged in a hierarchy, so that a subclass can inherit behavior from its superclass.

Java comes with an extensive set of classes, arranged in packages, that you can use in your programs.

Distributed
  • It has a spring-like transparent RPC ( Remote Procedure call ) system
  • Now uses mostly TCP/IP based protocols like ftp & http

Java supports various levels of network connectivity through classes in the java.net package (e.g. the URL class allows a Java application to open and access remote objects on the internet).

Interpreted

The Java compiler generates byte-codes, rather than native machine code. To actually run a Java program, you use the Java interpreter to execute the compiled byte-codes. Java byte-codes provide an architecture-neutral object file format. The code is designed to transport programs efficiently to multiple platforms.

  • rapid turn-around development
  • Software author is protected, since binary byte streams are downloaded and not the source code
Robust

Java has been designed for writing highly reliable or robust software:

  • language restrictions (e.g. no pointer arithmetic and real arrays) to make it impossible for applications to smash memory (e.g overwriting memory and corrupting data)
  • Java does automatic garbage collection, which prevents memory leaks
  • extensive compile-time checking so bugs can be found early; this is repeated at runtime for flexibility and to check consistency
Secure

Security is an important concern, since Java is meant to be used in networked environments. Without some assurance of security, you certainly wouldn’t want to download an applet from a random site on the net and let it run on your computer. Java’s memory allocation model is one of its main defenses against malicious code (e.g can’t cast integers to pointers, so can’t forge access). Furthermore:

  • access restrictions are enforced (public, private)
  • byte codes are verified, which copes with the threat of a hostile compiler
Architecture-Neutral
  • Compiler generates byte codes, which have nothing to do with a particular computer architecture
  • Easy to interpret on any machine
Portable

Java goes further than just being architecture-neutral:

  • No “implementation dependent” notes in the spec (arithmetic and evaluation order)
  • standard libraries hide system differences
  • the Java environment itself is also portable: the portability boundary is POSIX compliant
High-Performance

Java is an interpreted language, so it will never be as fast as a compiled language as C or C++. In fact, it is about 20 times as slow as C. However, this speed is more than enough to run interactive, GUI and network-based applications, where the application is often idle, waiting for the user to do something, or waiting for data from the network.

Multi-threaded

Java allows multiple concurrent threads of execution to be active at once. This means that you could be listening to an audio clip while scrolling the page and in the background downloading an image. Java contains sophisticated synchronization primitives (monitors and condition variables), that are integrated into the language to make them easy to use and robust. The java.lang package provides a Thread class that supports methods to start, run, and stop a thread, and check on its status.

Dynamic
Java was designed to adapt to an evolving environment:
  • Even after binaries have been released, they can adapt to a changing environment
  • Java loads in classes as they are needed, even from across the network
  • It defers many decisions (like object layout) to runtime, which solves many of the version problems that C++ has
  • Dynamic linking

Thanks.

In this article we try to explore about Java and it’s feature which may be help you to choose a better and powerful language to develop an application. Please follow me at social network as well.