09/22/14
Amdahl's Law

How to decide pool size for Thread Pools?

Thread pool is really an important topic to understand, if you are developing an application, which is designed with multithreading approaches. Thread pool is a pool of live worker threads. Worker thread is thread which accept a task, complete it and come back to thread pool to accept another task. Such way application can use already exist threads multiple time instead of creating new thread every time. By using thread pool in your application, you can boost its performance and utilize resource efficiently.

But in this article, we are not talking how to create thread pool and how thread pool works. For this you can read my other blog about thread pool. Right now we are just discussing about, how to decide pool size for thread pool? I mean, on which factors we could decide that how many threads, we should create in our thread pool for better time and resource utilization.

Most of the time people don’t think about pool size for their thread pool and they create any number of threads in pool with their choice without thinking much on it. But believe me, if you don’t know how to decide number of threads in pool that could be more dangerous and could spoil your performance and memory management badly. Therefore, we will discuss in this article on which factors thread pool size depends and how an appropriate pool size affects performance of your application?

There are few factors mentioned below on which thread pool size depends:

Available Processors: This is first and most important factor on which thread pool size matters a lot. Because the purpose behind creating thread pool or making any program multithreaded is to utilize all available resources like processors and unused CPU cycles. If your pool size would be less than available processors in your system means you are not using all available processors and not utilizing resources fully. On other side, if your pool size is greater than your available processer that means you are creating more threads which a thread pool can handle. It is not possible to provide CPU cycle to each thread that means you are wasting memory by creating such threads in pool which is not going to utilize by thread pool. There is one more overhead for thread pool to maintain scheduling for such extra threads. Therefore, ideal pool size is available processors (AP) in your system or AP+1. Here is an example, how to get number of processors available in your system using Java.

int poolSize  = Runtime.getRuntime().availableProcessors();

OR

int poolSize  = Runtime.getRuntime().availableProcessors() + 1;

This is ideal pool size, if your multithreaded task is kind of computation, where threads are not getting block, wait on I/O or some combination.

But if your task also includes some kind of blocking or waiting time then there is one more way to determine pool size for such tasks. That is explained in next section.

Behavior of Tasks: It is important to understand behavior of your task what you want to perform inside thread. If you have different category of tasks with different behaviors then consider you thread pool size according to that behavior. If your task is simple computation and do not obtain any blocking or waiting then you can consider number of available processors (AP)  or AP+1, as mentioned in above section.

But for tasks that also include I/O or other blocking operations, you need a larger pool size for that, since not all of the threads will be schedulable at all times, some will be in wait condition. In order to size the pool properly, you must estimate the ratio of waiting time to compute time for your tasks, this estimate need not be precise and can be obtained through profiling or instrumentation. Alternatively, the size of the thread pool can be tuned by running the application using several different pool sizes under a benchmark load and observing the level of CPU utilization.

The optimal pool size for keeping the processors at the desired utilization of CUP is:

N = Number of processor available in system.

U = Target utilization of CUP; 0 >= U <= 1.

W/C = Ration of wait and computation time.

Number of threads for thread pool can evaluate by this formula:

Number of Threads = N * U * (1 + W/C)

This is way you can estimate your suitable thread pool size.

Amdahl’s Law: In application development there are lots of tasks which cannot be perform totally concurrently, there are few tasks which need to be perform sequentially. Therefore it is important to understand, how much proportion of tasks can be executed concurrent and how much speed you would get after making that portion of task concurrent. Therefore, Amdahl’s law is very useful to determine how much speed up you would get if you are breaking up your task into parallelism and sequential.

According to Amdahl’s Law, if P is the proportion of task can be executed parallel then maximum speed up can get with N number of processors (threads) is:

Amdahl's Law

By applying Amdahl’s law you can determine how many threads can give you better result in case of concurrency.

 

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


08/6/14
Java

Why should use Java as programming language?

Java

Java is one of the most popular language of recent time. World wide programmers love Java and decided to pursue it as their programming language. But this is not the only reason to use Java as programming language. There are lots more reasons available to choose Java for your language. Lets see few most significant reasons to use Java as programming language.

1. Multi-platform  Support: Java is platform independent language and support multiple operating systems. Java does not confined you to specific operating system. Therefore, application written on Windows can easily run on Linux or Mac Operating systems.

2. Object Oriented Language: Java is one of most popular object oriented language, which supports all OOPs features as language. Java is pure object oriented language till very much extents except primitive datatypes.

3. Established Language: Java was first time introduced in 1995 and this is most established language. Huge number of applications development have done on Java and those applications are running successfully on production environment. This is one of most trusted language in IT industry.

4. Rich Libraries Support: Java provides huge numbers of built-in libraries to boost Java application development must faster and safer.

5. Big Community Support: There is big community support is available for Java programming language. Very huge number of programmers works on Java language world wide and provides support to Java community and help to find out suitable resolution for every problem.

6. Open Source Language: As you know Java is an open source language. Therefore, programmer can deeply understand language internals and take good advantage of it in his/ her programming.

7. Low Cost Development: Application developed in Java always has very low cost compare to other languages applications,  because Java and most of it’s frameworks, applications servers and web servers are free and open source. Which affects the application development and deployment cost very much.

8. Research on Java: Just because, Java is an open source language, world wide researchers are doing research on Java language and making it more powerful and robust day by day.

9. Framework Support: There are large numbers of frameworks available in market which supports Java language. Therefore, all applications based on Java can take advantages of these frameworks according to it’s needs. Lots of frameworks available like Spring, Hibernate, Struts, JUnit etc.

10. Memory Management: Garbage collection is one of big reason of Java success in IT industry. Java provide automatic memory management through garbage collection feature. Java has provided different verity of garbage collection algorithms according to applications need. These garbage collection algorithms gives very efficient automatic memory management.

11. Various Applications Development Support: Java is most admired language for developing applications for different types of environments. Java can be use for developing console applications, desktop applications, server side applications , web services, web applications and mobile applications (Android Apps) etc.

12. Application and Web Servers Support: Verity of  applications and web servers are available for Java applications like IBM WebSphere Application Server, WebLogic, JBoss Application Server, Apache Tomcat, Jetty etc.

13. Significant Required Features: Java has all significant and required features built-in, which are most demanded for any programming languages. For example, multi-threading, socket communication, memory managements and lots more, which make Java much more popular than any other language.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


06/25/14
java

Must Reads Books for Java Developers

Reading is always a good habit. Each and every book teaches us something that make us better person. But reading a good content is always beneficial. There are millions of books and contents available in market and internet to read about Java. But among them, there are few most recommended books for Java on specific topics. That is why, those books comes in list of “Must Reads Books for Java Developers”. These books are most appreciated and full of knowledge. Everyone, regardless his/ her experience on Java technologies must read these books once to become best Java developer. In this article, I would mention about good parts of these books, about authors and why these books are in list of “Must Reads Books for Java Developer”?

1. Effective Java, 2nd Edition by Joshua Bloch

Effective Java is one of the most recommended books by Java community. This book contains great topics about Java concepts. This is one of my favorite books. I have experienced that, sometime experienced professional says “If you didn’t read ‘Effective Java’ that means you are not serious about Java programming”. But despite of this comment, I will recommend this book as a must read book. This book is specially written for experienced Java developers, who have good coding experience on core Java. Most significant thing about ‘Effective Java’ is, this book doesn’t teach basics concepts of Java but it teaches you about best practices of Java and helps you to overcome most common mistakes that we made during programming, which help you to write best quality and most effective code in Java. ‘Effective Java’ contains each topic as isolated items, you can read any item of this book any time and these items are not dependent on each other. Jashua Bloch is author of ‘Effective Java’. He do works at Google. Jashua Bloch has great knowledge about API designing and author of well know ‘Java Collection API’. He has write done his great expertise and knowledge in this book. Hence, this book is must read book.

2. Java Concurrency In Practice, by Brian Göetz, Tim Peierls,  Joshua Bloch, Joseph Bowbeer, David Holmes & Doug Lea

‘Java Concurrency in Practice’ is one of my favorite books on Java. This book is specifically written for Java concurrency or multi-threading concepts. As all of you know, writing a multi-threading code is much more difficult as compare to sequential code. Therefore, this book deals with concurrent programming in Java. ‘Java Concurrency in Practice’ will explain each and every important topic on concurrent programming. I will strongly recommend this book for all those guys, who are interested to learn concurrent programming on Java. ‘Java Concurrency in Practice’ book is written by world’s best Java professional. Authors of this book are Brian Göetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. Hence, this is one most recommended Java book and comes in list of ‘Must reads books for Java Developers’.

3. SCJP 6, by Katherine Sierra & Bert Bates

SCJP 6 stands for, Sun Certified Java Professional. This book is specially written for Java 6 certification for Java, but this could be very nice book for Java beginners, who wants to learn basic Java concepts. SCJP 6 targets Java 6 concepts. This book fulfills dual purpose like, learning basic concepts of Java and Java certification preparation. Author of this book are Kathrine Seirra and Bert Bates, who were Java trainers and exam setter in Sun Microsystem. Both have written good content for Java Certification Preparation. Therefore this is must read book for Java beginners.

4. Cracking The Coding Interview, by Gayle Laakmann

‘Cracking The Coding Interview’ is the book for those guys, who are preparing for coding interviews for world’s best IT or financial companies. This book has very nice and important topics for preparing interviews. One of the important things about this book is that, this book teaches, what approaches need to be take care about during writing any algorithm. This book contains good collections of interview questions and algorithms. Anyone can read this book, regardless of any programming language experience. Author of this book is Gayle Laakmann, who was closely associated with world’s best IT companies. That is why, she has very nice idea of their recruitment processes and technical evaluation processes. With this knowledge, she is trying to help all people, who want to prepare for interviews of reputed companies. Gayle Laakmann is also a founder of website www.careercup.com. This website provides interview questions forum for those guys, who have queries regarding interviews. Hence, this is very nice book for interview preparation.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


06/23/14
Amazon

Hot Deals On Amazon

Promo

Mens Clothing – Launch Offer

Check out our brand new Men’s Clothing store and take advantage of our special launch offer – Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


Promo

30% off on Bluetooth Headsets

Save up to 30% off on Bluetooth Headsets by Samsung, Jabra, Plantronics and more.

Get Link:
30% off on Bluetooth Headsets


Promo

Save 30% on Power Banks

Keep your phone going. Save up to 30% on a wide range of Power Banks.

Get Link:
Save 30% on Power Banks


Promo

Up to 50% off on Routers

Get up to 50% off on Routers by D-Link, Netgear and more.

Get Link:
Up to 50% off on Routers


Promo

Deals on Tablets

Get up to 25% off on Tablets – Dell, Lenovo, Samsung, HCL and others.

Get Link:
Deals on Tablets


Promo

Games & Gaming Accessories

Save 25% off or more on a wide range of Games and Gaming Accessories.

Get Link:
Games & Gaming Accessories


Promo

Study Aids & Exam Preparations

25% off or more on study guides and exam prep books.

Get Link:
Study Aids & Exam Preparations


Promo

100 Must Read Books

The Amazon.com editors have put together a list of the 100 must-read books in a lifetime. Find great deals on your favourite title.

Get Link:
100 Must Read Books


Promo

Samsung Galaxy Tab 4 T331

Pre order the brand new Samsung Galaxy Tab 4 T331 at a special price.


Promo

Brand New Lava Iris X1

Exclusive Launch: Get the brand new Lava Iris X1 at Amazon.

Get Link:
Lava Iris X1


Promo

50% off on 1000+ Music Albums

Save up to 50% on 1000+ Music Albums – Rock, Classic, Pop, Ghazals and Bollywood.

Get Link:
50% off on Music


Promo

40% off on best-selling Video Games

Save up to 40% off on best-selling Video Games for PS3, Xbox 360 and other platforms.

Get Link:
40% off on best-selling Video Games


Promo

Up to 50% off on Fossil, Sony, Esprit & more

Get up to 50% off on select watches from Fossil, Sony, Esprit, Titan and other brands.

Get Link:
Best Deals in Watches


Promo

Great Deals in Electronics

Find great deals on Mobiles, Smartphones, Cameras, Tablets, MP3 Players, Headphones, Speakers and Electronics Accessories.

Get Link:
Great Deals in Electronics


Promo

Women’s Shoes under 799

Find hundreds of styles from a number of brands for under 799.

Get Link:
Women’s Shoes under 799


Promo

50% off on Bestselling Books

50% off on Bestselling Fiction, Autobiographies, Self-Help and more.

Get Link:
50% off on Bestselling Books


Promo

40% off on Audio & Video

Get up to 40% off on a wide range of iPods, Speakers and Headphones.

Get Link:
Deals on Speakers, Headphones & More


Promo

30% off on Baby Products

Save 30% off on a wide range of Baby Products.

Get Link:
Baby Products Deals


Promo

30% off on select Comedies

Browse our vast selection of English and Hindi comedies, and get an extra 30% off on select titles.

Get Link:
Extra 30% off on select Comedies


Promo

Additional 35% off on Shoes

Check out our newly launched Footwear store, and get an additional 35% off on select shoes by Nike, Fila and more.

Get Link:
Additional 35% off on Shoes


Promo

25% off on Cameras

Get up to 25% off on a wide range of Cameras, and EMI options on orders above Rs.3,000.

Get Link:
25% off on Cameras


Promo

50% off on Fashion & Traditional Jewellery

Get up to 50% off on Fashion and Traditional Jewellery.

Get Link:
50% off on Fashion & Traditional Jewellery


Promo

Up to 50% off on Headphones

Find the best prices on a wide range of Headphones from JBL, Philips, Skullcandy and more.

Get Link:
Up to 50% off on Headphones


Promo 

35% off on Popular Smartphones

Get up to 35% off on select Smartphones from Samsung, Nokia, Apple, Micromax and more.

Get Link:
35% off on Popular Smartphones

 


Promo

50% off on Blu-ray titles

Save up to 50% on select Blu-ray titles.

Get Link:
50% off on Blu-ray titles


Promo 

Up to 50% off on Speakers

Find the best prices on a wide range of Speakers from JBL, Creative, Sony and more.

Get Link:
Up to 50% off on Speakers

 


Promo

Home & Kitchen essentials

Get up to 25% off on select Home & Kitchen essentials.
Get Link:
25% off or more on Home & Kitchen Essentials

 

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


06/21/14
Java

What is Reentrant Synchronization or Locking in Java?

Java programming language supports multithreading or concurrency very well. Therefore, when we say multithreading or concurrent programming, it is necessary to have efficient synchronization or locking mechanisms, which saves concurrent program from unexpected concurrency issues like deadlocks. Reentrancy is one of those locking mechanism which help concurrent program to work as expected without any locking issue.

Now, you want to know, what exactly this reentrancy do in Java? Let me explain you reentrancy or reentrant locking in Java, but before moving on it, I would like to tell you about, how Java threads take locks on objects and make operation synchronize or atomic. Therefore, before moving on reentrancy, I would like to explain intrinsic or monitor lock.

Intrinsic Or Monitor Lock

Java provide built-in locking mechanism to make any operation atomic by synchronization in concurrent environment. In Java programming language ‘synchronized‘ keyword is used for taking lock or monitor on object. There are other locking utility also available in Java but we will concentrate on basic locking mechanism (synchronized) only. synchronized keyword can be use with method signature or with particular code block to make that synchronize. These built-in locks known as intrinsic or monitor lock.

Intrinsic Lock Examples

There are few intrinsic or monitor lock examples mentioned below to make code synchronized.
1. Creating object level lock with method signature.

public synchronized void objectLevelLock() {
	// Code to make synchronized or atomic
}

2. Creating object level lock with synchronized block inside method.

public void objectLevelLock () {
	synchronized(lockObject) {
		// Code to make synchronized or atomic
	}
}

3. Creating class level lock on static members of class with method signature

public static synchronized void classLevelLock () {
	// Static members and Code to make synchronized or atomic
}

4. Creating class level lock on static members of class with synchronized block inside method.

public void classLevelLock () {
	synchronized(ClassName.class) {
		// Static members and Code to make synchronized or atomic
	}
}

Reentrant Lock

Reentrancy is a locking mechanism provide by Java, which prevent Java locking from critical concurrency issue like deadlock . Suppose, there are two threads A and B. Thread B is trying to acquire lock or monitor on an object, which is already acquired by thread A. Thread B will be blocked until thread A release lock or monitor. But if thread A will try to acquire lock on other synchronized method or block on same object, it will be succeeded to acquire lock on same object. This facility is known as reentrancy. In other words, a thread who takes lock or monitor on object can be reenter any number of synchronized methods or blocks of same object on which it has already acquired lock. This is because, object locking is performed on per thread basis, not on per invocation basis.

What Could Be The Problem Without Reentrant Lock?

In this section I would like to explain, If reentrancy wouldn’t supported by Java, how it could affect thread execution and create concurrency issue. Please carefully go through the code given below.

public class Reentrancy {
	public synchronized void inner() {
		// Code to make synchronized or atomic
	}
	public synchronized void outer() {
		// Code to make synchronized or atomic
		inner();
	}
}

In this above code what will happen if reentrancy is not supported by Java. Suppose, a thread acquire lock on Reentrancy class object by invoking synchronized method outer(). But if you would notice outer() method invoking inner() method, which is also synchronized method. In such case, if Java wouldn’t support reentrancy, outer() method couldn’t succeeded to acquire lock on inner() method, because, it would be considered already locked and eventually result would be deadlock. But just because reentrancy is supported in Java, the thread who acquire lock on object can enter any synchronized method or block on same object to acquire lock.

How Reentrant Lock Works In Java?

Reentrancy is implemented in Java by associating a counter with each thread. Initially counter initialized with value zero and considered as unlocked. When thread acquires lock on an object, counter get incremented by one. Again, if thread acquires lock on another synchronized method or block, counter again get incremented by one; counter will become two and so on. Same reverse process is followed, when thread release lock by leaving synchronized method or block. When thread releases lock from synchronized method or block; counter get decremented by one and so on. Once again, when counter reached to zero; object gets unlocked. Now other threads are free to acquire lock on that object. This is the approach by which Java manage reentrancy.

Conclusion

That’s all how Java intrinsic and reentrant lock works. After reading this article, you are aware about, what are intrinsic and reentrant locks and how these locks works. I hope this article will help you to understand about Java locking mechanism.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


06/12/14
author

UML relationships like Association, Aggregation, Composition, Abstraction, Generalization, Specialization, Realization and Dependency

In this article, we are specifically taking about few Object Oriented Programming relationships like association, aggregation, composition, abstraction, generalization, specialization, realization and dependency. These relationships are very common for any object oriented programming. Despite of that, lots of developers feels that these terms are little weird and unknown for them. In this article, I would try to explain each and every term with suitable examples. I hope after reading this article few of you would be amazed that these all relationships are so familiar to you. But you do not know them so closely. But after reading this you can understand these relationships very well. These relationships are very important and useful in UML to demonstrate relationships between classes and objects. So let us explore these topics one by one.

Association

In Object Oriented Programming, each object shared some kind of relationships with other objects. Therefore, relationship between objects is known as “Association”. This relationship could be any type like one-to-one, one-to-many or many-to-many. For example, Student and Subject relationship. Relationship between Student and Subject is many-to-many, because one Student can read many Subjects and one subject can be read by many Students. Therefore, Students and Subjects are associated with each other.

Aggregation

Aggregation is special type of association, in which one object contain other object, which is directional relationship. This relationship is also known as “has a” relationship. For example, every Employee has a Department. Therefore, there is an aggregation between Employee object and Department object.

Composition

Composition is special case of aggregation. In this relationship, one object contain other object. This is also a “has a” relationship. But there is one restriction with this relationship, that is, contained object can’t exist without container object. For example, Person has a Address, but Address does not have any importance and can’t exist without Person. Therefore, a Person compose an Address.

Abstraction

Abstraction is one of the important concepts of Object Oriented Programming. Abstraction is to hiding implementation information from user. Instead of exposing implementation, its declare methods or functions and their general detailed information to help implementation. Later on user can provide concreteness by giving correct implementation based on details information provided by abstract layer. Examples of abstraction are Abstract classes and Interfaces.

Generalization

Generalization is a relation between Superclass and Subclass . This relation is “is a” relationship . Generalization is process of moving common code from Subclasses to Superclass. This process will make that common code to general code. So that, this general code can be reuse by any of its Subclass. Generalization is type of inheritance.

Specialization

Specialization is a process of creating a new subclass of existing superclass. In specialization, subclass extends existing general implementation to specific implementation by overriding existing implemented methods. This is also “is a” relationship. Specialization is type of inheritance.

Realization

Realization is a relationship between interface and class. In realization, new class implements all unimplemented abstract methods and provide concrete implementation. This process provides real business logic implementation to any abstract class or interface. This is also “is a” relationship.

Dependency

Dependency is relationship between two or more classes, in which, if any modification done on one class can affect other classes. That means one class depends on second clas . In such way one class has dependency on second class.

Symbols Used By UML To Show Relationships Between Classes Or Objects

UML Symbols

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


05/30/14
author

How to make any class immutable in Java?

Immutability is most important topic in respect of coding practice. This is one of the frequently asked topic in Core Java interview. Every interviewer expect that you must have good understanding about immutable classes, advantages of immutable classes and very important that how to create any class immutable in Java. These are few important aspects, which is necessary to know about immutable objects. In this article, I would divide it into three parts, so that you can have better understanding about immutability level by level. Let us talk about immutability concept deeply.

Immutable class in Java

1. What Is Immutable Class?

As you know general meaning of “immutability” in English is “A quality, not to being changeable”. Same a class called immutable, only if it’s internal state never change once it is initialized. When a immutable class get initialize, it create its internal state ( initialize it’s data members ) at the time of initialization by passing arguments through constructor. Once an immutable object get initialized, nobody can changes its internal data members. In Java there are lots of classes, which are immutable in nature, like java.lang.String, java.lang.Integer, java.lang.Double etc.

2. What Are The Advantages Of Immutability?

This is really a nice question that why should we create immutable class? or what are the advantages of immutable class?

The main reason to make any class immutable is it’s internal state safety. Immutable classes are thread-safe. Immutable objects can be passed to untrusted code. Biggest worry in multi-threading environment is that any mutable object shared between threads can spoil its state unpredictably. But immutable objects are totally safe to share between threads.

Second advantage is that its simple to make any class immutable by following some set of simple rules. There are predefined rules which are necessary to follow to protect object state. We will cover all these rules in next section of this article.

Third advantage is that we don’t need to implement cloning on immutable class. We can share same copy anywhere. Because, immutable objects don’t change it’s state anyhow. If you want to learn about cloning, you can read my article, What is cloning and types of cloning in Java?

3. How To Make A Class Immutable?

As of now, you know what is immutability. But how can we make any class immutable in Java? There are some set of rules, which we need to follow at the time of creating any immutable class. In this section we will go through all important rules, what we need to care about and will understand how these rule can make any class immutable. Lets see how we can make a class immutable. Before that, I would like to show you one simple class example (Immutable Class), which gives you an idea, how an immutable class look like and why we say it immutable.

import java.util.ArrayList;
import java.util.List;

public final class Immutable {
	// int is primitive data type.
	private final int value;
	// String is immutable class;
	private final String text;
	// List is mutable type.
	private final List<String> list;
	
	public Immutable(int value, String text, List<String> list) {
		this.value = value;
		this.text = text;
		this.list = copyOfList(list);
	}
	
	public int getValue() {
		return value;
	}
	
	public String getText() {
		return text;
	}
	
	public List<String> getList() {
		return copyOfList(list);
	}
	
	private List<String> copyOfList(List<String> list) {
		List<String> newList = new ArrayList<String>();
		for ( String element : list )
			newList.add(element);
		return newList;
	}

}

Please understand this above example carefully, because in next step, I will use this example to explain all important rules regarding immutability. Lets talk about the immutability rules in detailed manner:

  1. All data members inside class must be private.  Because, private data members cannot access from outside of the class. Therefore, nobody can access and change the state of internal data members.
  2. All data members inside class should be final. It is a good coding practice, but this is not hard and fast rule. Because immutable class don’t allow to access any data member of immutable class outside. Therefore, It doesn’t meter that whether data members of class are final or not.
  3. All data member must be set through constructor. No setter method will be provided for any data member. Because, if class will provide setter methods then anybody can change immutable objects state.
  4. Class must be declared as final. So that no other class can extend this class and spoil its immutability. Now, there could be one question in your mind, how can we break immutability by extending non final class? Lets me show you an example:
    public class Immutable {
         private final Object value;
    
         public Immutable(Object value) {
             this.value = value;
         }
    
         public Object getValue() {
             return value;
         }
    }
    public class Mutable extends Immutable {
         private Object realValue;
    
         public Mutable(Object value) {
             super(value);
             realValue = value;
         }
    
         public Object getValue() {
             return realValue;
         }
    
         public void setValue(Object newValue) {
             realValue = newValue;
         }
    }

    Here you can see how extended class Mutable can pass its own Object in it’s superclass Immutable constructor. Now Mutable class can easily break immutability of Immutable class by changing its own Object. That is why it is significant to make class final.

  5. All mutable objects coming in through constructor should not use directly, instead of that, create new object copy of that object, which must be equal to passed object. As you can see in my topmost coding example (Immutable Class), inside constructor I have used this.list = copyOfList(list);  instead of using this.list = list; Here I have create an copy of list object rather than passing it directly.
  6. All mutable objects going outside through getter methods must return new copy of mutable object instead of returning same object outside. New returned copy object must be equal to the original object. As you can see in my topmost coding example (Immutable Class), I have used return copyOfList(list); inside getList() method instead of using return list; Because I don’t want to share my internal reference to outside the world.
  7. But primitive and immutable reference can be used directly and can be shared outside the world without any hesitation. Because primitive and immutable reference cannot change anyhow. 

Conclusion

That is all about immutability concept. By reading this article, you know about immutability, advantage of immutability and all important rules to make class immutable. This concept don’t belong to any specific language. You can follow these rules to make your class immutable in any language. I hope this article will encourage you to use immutability in your coding practices.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


05/23/14
author

What is cloning and how many types of cloning exist in Java?

There are lots of ways to create objects in Java. You can create an object by new keyword with constructor, by Java reflection, by Java deserialization to a serialized object and by Java cloning. But here we are specially taking about Java cloning. Java cloning is process to create an exact copy of an object or clone of an object. Java cloning creates copy of an object without invoking any construct. There are two types of cloning in Java Shallow Copy and Deep Copy cloning. I will discuss these topics later-on in this article. Java cloning is an controversial topic in Java. Lots of people do not think that cloning is a best implementation in Java. But we are not talking about that controversy here, instead of that we are discussing on present cloning feature in Java and its mechanism.

How To Create A Class Clone-able?

There are few requirements to create a class clone-able. First of all your class must implement java.lang.Cloneable interface, which is a marker interface in Java. Therefore, java.lang.Cloneable interface does not declare any abstract method, this is an empty interface, which tell the JVM that, this class supports cloning mechanism. If class doesn’t implement java.lang.Cloneable interface then it will throw java.lang.CloneNotSupportedException. This is a checked exception in Java, which is mandatory to handle during cloning.

Second and important requirement is to override clone() method of java.lang.Object class. This method is declared as protected and native in java.lang.Object class. Therefore clone() method create clone of object by calling super.clone() method of its parent class and eventually it will call the clone() method of java.lang.Object class. As I told you earlier that cloning process does not invoke constructor of class to create copy of object. That is why cloning use native approach to initialize new object and equal object in memory.

Important Aspects About Java Cloning

As you know Java cloning is a process to create a exact copy of an object. But there are some important aspects and contract between original object and cloned object. Which is really significant to understand before writing cloning mechanism in Java. Lets talk about them.

  1. To support cloning in Java, class must implement java.lang.Cloneable interface.
  2. After implementing java.lang.Cloneable interface, class must override clone() method of java.lang.Object class.
  3. Cloning should not use constructor to create copy of object. You can use native approach to initialize new cloned object.
  4. Cloned object must be a new object in memory. clone() method should not return same instance (this) on which clone() method is invoked. Therefore x == x.clone() must be false.
  5. x.getClass() == x.clone().getClass() will be true, But its not an absolute requirement.
  6. Cloned object must have same internal state as it’s original object. Both original and cloned object’s  data members must have similar state or value. Therefore,  x.clone().equals(x) must be true.
  7. Checked exception java.lang.CloneNotSupportedException must be handled at the time of cloning.

Java Cloning Implementation Example

public class Foo implements Cloneable{
	
	private int number = 0;

	public void setNumber(int number) {
		this.number = number;
	}

	public int getNumber() {
		return number;
	}
	
	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}

Types Of Cloning In Java

Now you know, what is cloning and all significant aspects about cloning in Java. But types of cloning is also very important aspect in Java. It is most important, if you want to implement clone-able class by yourself.

There are two types of cloning in Java and both have significant differences.

  1. Shallow Copy
  2. Deep Copy

 Shallow Copy

Shallow copy is a new copy (clone) of original object, but all internal variables of new cloned object are same as original object. Java by default create shallow copy during object cloning. As you have seen above  in Foo class example, Foo class’s override clone() method call super.clone() native method of java.lang.Object class. That’s mean native clone() method of java.lang.Object class assign similar internal variable reference of original object to cloned object’s variable. In that case, we have two different objects but internally they holding same references as their data members. Means variables of original object and cloned object both referring same objects on heap. This technique is correct if your class holding only primitives or immutable objects, but this technique goes wrong, if your class hold any mutable object. Because any change made on mutable reference of original object will be reflect on  cloned object or vice-versa. Therefore, shallow copy technique somewhere breaking cloning purpose. In such way original object and cloned object are not totally independent, somewhere both are dependent on each other. You can see below diagram, how original and shallow copy objects share internal references.

Java Shallow Copy Cloning

Lets see shallow copy example and its disadvantage.

public class Foo implements Cloneable{
	// Primitive Reference
	private int number = 0;
	// Immutable Reference
	private String name;
	// Mutable Reference
	private Bar bar;
	

	public void setNumber(int number) {
		this.number = number;
	}

	public int getNumber() {
		return number;
	}
	
	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
	
	public void setBar(Bar bar) {
		this.bar = bar;
	}

	public Bar getBar() {
		return bar;
	}
	
	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}

ShallowCopyCloneTest.java class shows that, how should we create a clone object from cloneable class. This class will also put some light on problem exist in shallow copy technique.

public class ShallowCopyCloneTest {

	public static void main(String[] args) {
		try {
			Bar bar = new Bar();
			bar.setValue("Hi");
			Foo object = new Foo();
			object.setNumber(20);
			object.setName("Hawk");
			object.setBar(bar);
			
			Foo	clone = (Foo) object.clone();
			
			System.out.println("Foo Orignial# Number:" + object.getNumber() + " Name:" + object.getName() +" Bar-Value:" + object.getBar().getValue());
			System.out.println("Foo Cloned# Number:" + clone.getNumber() + " Name:" + clone.getName() +" Bar-Value:" + clone.getBar().getValue());
			
			object.setNumber(40);
			object.setName("Eagle");
			object.getBar().setValue("Hello");
			object.setBar(bar);
			
			System.out.println("Foo Original Object Changed....");
			
			System.out.println("Foo Orignial After Change# Number:" + object.getNumber() + " Name:" + object.getName() +" Bar-Value:" + object.getBar().getValue());
			System.out.println("Foo Cloned Without Change# Number:" + clone.getNumber() + " Name:" + clone.getName() +" Bar-Value:" + clone.getBar().getValue());

		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
	}
}

Output after running shallowCopyCloneTest.java class

Foo Orignial# Number:20 Name:Hawk Bar-Value:Hi
Foo Cloned# Number:20 Name:Hawk Bar-Value:Hi
Foo Original Object Changed....
Foo Orignial After Change# Number:40 Name:Eagle Bar-Value:Hello
Foo Cloned Without Change# Number:20 Name:Hawk Bar-Value:Hello

If you would see the code and output carefully, you can understand that cloned object looks like exact copy of original object before any modification done on original object. But after making modification on original object ‘Number’ and ‘Name’ data member of cloned object doesn’t get change, because ‘Number’ is primitive data type and ‘Name’ is String type, which is immutable in Java, that mean they are safe to share between objects. But ‘Bar-Value, of cloned object get changed itself with modification on  ‘Bar’ reference of original object, this is because ‘Bar’ reference is mutable, which is not safe to share between objects. This is how shallow copy break rule of cloning that both original and cloned object should be conceptually equal and independent. Modification on one object should not reflect on other object.

Deep Copy

Deep copy cloning is a solution for references sharing problem of shallow copy cloning. Deep copy cloning is very important and useful cloning technique, which takes guaranty that cloned copy will be an equal object as original object and both objects will be totally independent, that means no internal references will be shared (Modification on original object will not affect cloned object any more or vice-versa). In deep copy cloning all mutable variables further get manual deep cloned before returning cloned object to client. This is the responsibility of class author that if your class is cloneable, then you will use deep copy cloning techniques, so that your class can return deep copy as cloned object. But somewhere we have to compromise with some basic cloning rules, like “We should not use constructor during cloning”. But if we have to create deep copy cloning, somewhere we have to use constructor to create deep copy object, that means we have to create new references for cloned object.

Java Deep Copy Cloning

Here, I would like to use an best example, which is illustrated by Jashua Bloch in his book “Effective Java” . This is an amazing book for Java concepts. Everyone must read this book once.  In this simple example he has shown that how java.util.HashTable class has implemented deep copy cloning inside this class. In java.util.HashTable class Entry[] array is an mutable reference, which is deep cloned by deepCopy() method. Go through this example, it will give you a good idea about, how should we create deep copy for a cloned object.

public class HashTable implements Cloneable {
    private Entry[] buckets = ...;

    private static class Entry {
        final Object key;
        Object value;
        Entry next;
        Entry(Object key, Object value, Entry next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }

        // Recursively copy the linked list headed by this Entry
        Entry deepCopy() {
            return new Entry(key, value,
                    next == null ? null : next.deepCopy());
        }
    }
    @Override 
    public HashTable clone() {
        try {
            HashTable result = (HashTable) super.clone();
            result.buckets = new Entry[buckets.length];
            for (int i = 0; i < buckets.length; i++)
                if (buckets[i] != null)
                    result.buckets[i] = buckets[i].deepCopy();
            return result;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
}

Conclusion

That is all about Java cloning. In this article you have understand basic requirement for cloning, all important rules to implement cloning. You have read about differences between shallow copy and deep copy cloning. Now you know what types of problems, you may encounter with in case of shallow copy cloning. But most important thing is that, Now you have a good idea about deep copy cloning and you know what approach you should take to write your own deep copy cloning approach. I hope this article will help you somewhere to write correct and robust code.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


05/4/14
author

What is Bridge Method and Type Erasure in Java Generics?

Bridge method and type erasure in Java generics are advance concepts. These concepts are important for experienced Java professionals. These are basically a low level typics, I mean Java Bytecode compilation level topics. Therefore, It is necessary that you must have good understanding of Java generics and it’s implementation before going more deep in these concepts. Bridge method and type erasure are really interesting topics in Java. After reading this article, you would be amazed that how generics classes work internally. Apart from that, these topics are also important for all experienced Java professionals, who wants to have good understanding behind Java Generics. Because, most of interviewers would expect from you that you would have understanding of JVM internal execution and Java Bytecode compilation. If you are really interested to know, let us talk about bridge method and type erasure.

java bridge method

But before going on these topics let us understand what is Java generic and how does generic works behind? When we do create generics classes or interfaces, they do not declare any concert types, while they do not aware of, what kind of objects they will contain at real time. But we tell and specify to generic type,  some specific concert objects types at the time of compilation. These specific concert objects types declaration occurs, when we actually extends, implements and use these generics classes or interfaces. But now question arise, if generics classes or interfaces do not know about concert objects on which they have to perform operations, then how do they manages their internal execution without knowing their concert types? Answer of this question is by type erasure. Lets take a generics coding example to illustrate this.

public interface Foo<T> {

     public void setName(T name);

     public T getName();
}

public class Bar implements Foo<String> {

     private String name;

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

}

In this example you can see that  Foo<T> interface is generic type and its implementation Bar class can use any kind of concert object in its implementation, here we have used String type object for Bar class implementation. Now you can see that generic type setName and getName methods can accept and return String types objects. But how any generic types can accept any specific concert objects. This problem can be resolve by using type erasure.

Type Erasure In Java

Type erasure is a process to map a generic parameter type or method to its unique bytecode representation.

The compiler generates single unique bytecode representation for generic type or method by eliding type parameters and arguments. All instances of generics types get mapped with unique bytecode representation. This unique bytecode representation is created by type erasure. To create an unique bytecode representation, compiler elide generic type to java.lang.Object type (List<T>  → List<Object>), which can accept any kind of objects. If generic type is extended by one of specific type then it is elide to that specific type (List<T extends Animal> → List<Animal>).

Bridge Method In Java

Bridge method is a auto-generated method or unique representation generated by compiler after type erasure to any generic type method. These bridge methods are unique bytecode representations which are used to perform generic operations.

The compiler insert a bridge method in sub class of generic super class by type erasure. So that sub class can work as expected. Lets see bridge methods example.

public interface Foo {
	// Bride Method Declaration By Type Erasure
	public void setName(Object name); 
	
	// Bride Method Declaration By Type Erasure
	public Object getName();

}

public class Bar implements Foo {

	private String name;
	
	public void setName(String name) {
		this.name = name;
	}
	
	// Bride Method Declaration By Type Erasure
	public void setName(Object name) {
		this.setName((String) name);
	}
	
	public String getName() {
		return this.name;
	}
	
	// Bride Method Declaration By Type Erasure
	public Object getName() {
		return this.getName();
	}
}

After type erasure conversion by compiler setName(String name) is not implementation of Foo interface. Because Foo interface required setName(Object name) implementation, which is introduced by compiler as bridge method. Therefore bridge method provides accurate implementation. But these bridge methods delegate original methods internally in bridge methods. Bridge methods can not access by client directly, because Java do not expose bridge methods for user to use. But still there is a way to break this rule. Because bridge methods can access by Java reflection. Through refection you can even invoke private methods of class, same you can invoke bridge methods of class through reflection as well.

This is how generic type classes or interface transform from generic type to any specific type. In this conversion bridge method and type erasure play an important role. Without bridge methods it would not be possible to map concert type objects with generics types. I hope you would like this post and this post will help you to understand mechanism behind generics.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


04/16/14
author

What is assertion or assert in Java?

Assertion or assert is a less known feature of Java. Most of developers don’t use assert in their daily routine coding, that is why most of developers don’t much bother about it. But frankly speeking, this is a useful feature of Java and every developer need to know about it. Most of you, who have used JUnit framework for unit testing, have used assertion to test any test case. JUnit is the best example of Java assertion. Lets discuss little more about assertion in Java. Since JDK 1.4, Java has introduced assert keyword to support assertion. Assertion is basically used for validation checks in program, if validation fails during assertion check, it throw AssertionError and program got terminated, otherwise it allow program execution as usual.

What Is Assertion?

Assertion facility introduced in Java since JDK 1.4. Java introduced assertion by assert keyword. An assertion is a boolean expression that a developer specifically proclaims to be true at runtime.

There are two forms of assertion in Java

assert Expression1;
or
assert Expression1 : Expression2;

Expression1 must be a boolean expression, which is evaluated at runtime, if it is false, an AssertionError is thrown.
Expression2 value is typically a String, but could also be anything that expression returns. This expression must not return void. It is basically used to customize message for AssertionError.

Note: AssertionError is an error, which is subclass of java.lang.Error class and not recoverable. It is used for logging purpose only.

assertion

Where To Use Assertion?

An assertion is a statement, which assumed to be true during the execution of program. It returns a boolean result. If result is true, code executes normally. Otherwise it throw AssertionError and terminate program execution. Assertion is basically validate the result. It is good to use assertion with one of the following:

1. Precondition is a assert condition which must be true, when method is invoked. If an argument is invalid for any method, its validation before using it in method is known as precondition check.  Precondition assertion check must be use in non-public methods. For public methods you must throw IllegalArgumentExcetption.  Because, public methods can be invoked by any client code, if client is invoking any method with illegal value then client must be informed by exception that passed value as argument is illegal for this method. If we use assertion instead of exception here, client would not be aware about his/ her mistake. Therefore precondition assertion must be use for non-public methods. For example. 

private void myMethod(int arg) { 
assert arg>0 && arg <=1000 : “Bad arg: ”+arg; 
… 
}

2. Internal Invariant is an assumption of program behavior. If somewhere in program any abnormal condition occurs that you can check with assertion. For example.

if (x%3 == 0) { 
… 
} else if (x%3 == 1) { 
… 
} else { 
 assert x%3 == 2 : x; 
 // x modulo 3 should be only 0, 1 or 2. Everything 
 // would work fine until you get negative x’s. 
 // *A simple assertion help to discover unsupported results. 
} 

//-------------------------------------- 
switch (key) { 
case CST_VALUE_A : 
 … 
 break; 
case CST_VALUE_B : 
 … 
 break; 
 … 
 default: 
 assert false : key; 
 // *A simple assertion help to discover unsupported values. 
}

3. Postcondition is a assert condition which, must be true, when method is about to finish its work and ready with final resultant. If final result ready to return, its validation before return by method is known as postcondition check.  Postcondition assertion check can be use in public or  non-public methods.

public double square(double val) { 
 .. // compute square 
 assert result*result == val : val; 
}

4. Class Invariant is type of internal invariant, which must be true with every instance of class. For example implementation of heap. Heap must be balanced with every instance is created inside it.

private boolean balanced { 
 … 
} 

public void addValue(double key, Object obj) { 
 … // implementation all method should check if heap is balanced prior to its return. 
 assert balanced(); 
}

5. Control Flow is a assertion check that would check a location that will never be executed.

if (…) {
…
return;
}
assert false; // should never be reached

Where To Avoid Assertion

There are few situations, where it is recommended to avoid assertion. Following are the situations:

  • Argument checking for public method by assertion is not recommended. Reason behind this is same, what is mentioned in precondition,s description.
  • In your application where you required correct operation, you must avoid assertion there. Expression evaluation during assert code can be harmful.
  • Evaluating the expression should not affect any state that is visible after the evaluation is complete. There is one exception in this rule is that assertion can modify the state that is used only form within other assertions.

Differences Between Exception and Assertion

Exception Assertion
Exception tells the programmer that something gone wrong in the program. Assertion document or log the program, when it fail and tell that program has bug.
Exception are created to inform and deal with problems which might occur in program. Assertion are create to validate accuracy of program.
Exception are used to test input or output as well as whether the program is legal or not Assertion are used to document and find bug in program. Assertion are also used for debugging purpose.

Important Points about Assertion

  •  Assertion is introduced since JDK 1.4.
  • In order to compile class with assertions using javac compiler, you must use the -source 1.4 command-line option as in this example:
     javac -source 1.4 MyClass.java

    This flag is necessary so as not to cause source compatibility problems.

  • Assertion can be enable and disable at runtime by using switches -enableassertions or -ea and -disableassertions or -da.
  • Running 1.4 binaries needs a 1.4 runtime engine. Assertion are default disabled. To
    activate them, use the following syntaxes:

    Syntax Purpose
     java -ea  Enable assertions in all classes excepted system classes
     java –ea:<className>  Enable assertions for a specific class
     java –ea:<packageName>…  Enable assertions for a package and any sub-packages
     java –ea:…  Enable assertions in the unnamed package in the current working directory
     java -da  Disable assertions (default)
     java –da:<className>  Disable assertions for a specific class
     java –da:<packageName>…  Disable assertions for a package and any sub-packages
     java –da:…  Disable assertions in the unnamed package in the current working directory
     java -esa  Enable assertions in system classes
     java -dsa  Disable assertions in system classes

     

Conclusion

That’s all about Java assertion. After reading this article, you understand Java assertions, where to use assertions, how to use assertion and where should avoid using assertions. I hope you will use assertions in your programs to make them more robust.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.