Multithreading in real world


Most of you already know about threads and it’s benefits. This article will help you to understand how thread are being used in real world applications and what are the best practices. Threads are primarily used to achieve asynchronous  behavior and multitasking.

Below are some common real life use cases where threads have been used effectively.

  1. Animation and Games.
  2. Most of the GUI tools like Swing uses thread to keep track of events generated from widgets.
  3. Internally Junit uses threads for executing test cases parallel.
  4. Most of the web servers uses multithreading to entertain HTTP Requests parallel

Below are some common best practices for developing concurrent (multi threaded )applications.

Naming a Thread-

Thread should be named for easier debugging.  You can see in Eclipse that threads running in parallel with some random names like “Thread-124362563”. Giving a unique name to a thread will make it easier to identify the thread while debugging.

How many threads-

Before deciding number of threads to create , please keep in mind following facts.

  1. One processor executes a thread at a time and keeps switching between threads. Too much of switching can be an inefficient solution.
  2. Now a days most of the computers are multi core i.e comes with multiple processor so multiple threads can be executed simultaneously.

For long running threads one practice  can be to have no of processors as no of threads.

Use Immutable Classes 

Immutable classes, once created cannot be modified so one does not need to worry about sharing the state with multiple threads. This reduces  a great scope of synchronization.

Threads VS JMS –

I have developers discussing JMS VS Threads for developing asynchronous behavior.  I think JMS is more controllable way to use threads. JMS gives you additional features like tracking of request and retry to make a better enterprise choice.

Use Executors instead of Threads API

Object pool is a concept to avoid cost of object creation and destruction. JDK provides “Executors” as managed thread pool.

Use  java.util.concurrent

Java 5 added a java.util.concurrent  to the Java. This package contains a set of classes that makes it easier to develop concurrent scalable applications .Before this package was added , one need to use “synchronized” , “volatile” , “join” , “wait” and “notify” to write concurrent ( multi threaded applications) .

Popular items of “java.util.concurrent” are “BlockingQueue” , “semaphore” , “Lock Interface”  , “CountDown Latch” and “CyclicBarrier”.

Giving some details about Locks , CountDown Latch and Cyclic Barrier.

Locks

Prior to java 5  “synchronized” and “volatile” were the means of achieving concurrency. “Synchronized” provides a clean way to code but comes with limitation like try lock i.e. acquire only if lock is available. For more scalable concurrent solution JDK added lock interface and various implementations. “Reentrant lock” is a popular implementation of Lock interface.

Synchronized acquired a intrinitc lock on object wihis realeased automaticaaly. Bot with Lock , one need to release a lock programiticaaly. Best practice is to relase the lock in try block.

Synchronized acquired a intrinitc lock on object wihis realeased automaticaaly. Bot with Lock , one need to release a lock programiticaaly. Best practice is to relase the lock in try block.

CyclicBarrier and CountDown Latch

Both CyclicBarrier and CountDown latch are used for thread synchronization i.e. thread waits for another thread to complete their job at some point. Difference between both is that Cyclic Barrier instance can be reused while CountDownLatch instance can not.

 

 

 

 

 

 

Advertisements

How HashMap works in Java


Note: Original article – http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html

How HashMap works in Java

How HashMap works in Java or sometime how get method work in HashMap is common interview questions now days. Almost everybody who worked in Java knows what hashMap is, where to use hashMap or difference between hashtable and HashMap then why this interview question becomes so special? Because of the breadth and depth this question offers. It has become very popular java interview question in almost any senior or mid-senior level java interviews.

Questions start with simple statement 

“Have you used HashMap before” or “What is HashMap? Why do we use it “

Almost everybody answers this with yes and then interviewee keep talking about common facts about hashMap like hashMap accpt null while hashtable doesn’t, HashMap is not synchronized, hashMap is fast and so on along with basics like its stores key and value pairs etc.

This shows that person has used hashMap and quite familiar with the functionality HashMap offers but interview takes a sharp turn from here and next set of follow up questions gets more detailed about fundamentals involved in hashmap. Interview here you and come back with questions like

“Do you Know how hashMap works in Java” or

“How does get () method of HashMap works in Java”

And then you get answers like I don’t bother its standard Java API, you better look code on java; I can find it out in Google at any time etc.

But some interviewee definitely answer this and will say “HashMap works on principle of hashing, we have put () and get () method for storing and retrieving data from hashMap. When we pass an object to put () method to store it on hashMap, hashMap implementation calls

hashcode() method hashMap key object and by applying that hashcode on its own hashing funtion it identifies a bucket location for storing value object , important part here is HashMap stores both key+value in bucket which is essential to understand the retrieving logic. if people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in HashMap . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge how hashing works and how HashMap works in Java.

But this is just start of story and going forward when depth increases a little bit and when you put interviewee on scenarios every java developers faced day by day basis. So next question would be more likely about collision detection and collision resolution in Java HashMap e.g 

“What will happen if two different objects have same hashcode?”

Now from here confusion starts some time interviewer will say that since Hashcode is equal objects are equal and HashMap will throw exception or not store it again etc. then you might want to remind them about equals and hashCode() contract that two unequal object in Java very much can have equal hashcode. Some will give up at this point and some will move ahead and say “Since hashcode () is same, bucket location would be same and collision occurs in hashMap, Since HashMap use a linked list to store in bucket, value object will be stored in next node of linked list.” great this answer make sense to me though there could be some other collision resolution methods available this is simplest and HashMap does follow this.

But story does not end here and final questions interviewer ask like 

“How will you retreive if two different objects have same hashcode?”

Interviewee will say we will call get() method and then HashMap uses keys hashcode to find out bucket location and retrieves object but then you need to remind him that there are two objects are stored in same bucket , so they will say about traversal in linked list until we find the value object , then you ask how do you identify value object because you don’t value object to compare ,So until they know that HashMap stores both Key and Value in linked list node they won’t be able to resolve this issue and will try and fail.

But those bunch of people who remember this key information will say that after finding bucket location , we will call keys.equals() method to identify correct node in linked list and return associated value object for that key in Java HashMap. Perfect this is the correct answer.

In many cases interviewee fails at this stage because they get confused between hashcode () and equals ()and keys and values object in hashMap which is pretty obvious because they are dealing with the hashcode () in all previous questions and equals () come in picture only in case of retrieving value object from HashMap.

Some good developer point out here that using immutable, final object with proper equals () and hashcode () implementation would act as perfect Java HashMap keys and improve performance of Java hashMap by reducing collision. Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g Integer provided by Java Collection API are very good HashMap keys.

Now if you clear all this java hashmap interview question you will be surprised by this very interesting question “What happens On HashMap in Java if the size of the Hashmap exceeds a given threshold defined by load factor ?”. Until you know how hashmap works exactly you won’t be able to answer this question.
if the size of the map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Java Hashmap does that by creating another new bucket array of size twice of previous size of hashmap, and then start putting every old element into that new bucket array and this process is called rehashing because it also applies hash function to find new bucket location. 

If you manage to answer this question on hashmap in java you will be greeted by “do you see any problem with resizing of hashmap in Java” , you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the java hashmap and potentially looking for race condition on HashMap in Java

So the answer is Yes there is potential race condition exists while resizing hashmap in Java, if two thread at the same time found that now Java Hashmap needs resizing and they both try to resizing. on the process of resizing of hashmap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because java hashmap doesn’t append the new element at tail instead it append new element at head to avoid tail traversing. if race condition happens then you will end up with an infinite loop. though this point you can potentially argue that what the hell makes you think to use HashMap in multi-threaded environment to interviewer 🙂

I like this question because of its depth and number of concept it touches indirectly, if you look at questions asked during interview this HashMap questions has verified

Concept of hashing

Collision resolution in HashMap

Use of equals () and hashCode () method and there importance?

Benefit of immutable object?

race condition on hashmap in Java

Resizing of Java HashMap

Just to summarize here are the answers which does makes sense for above questions

How HashMAp works in Java

HashMap works on principle of hashing, we have put () and get () method for storing and retrieving object form hashMap.When we pass an both key and value to put() method to store on HashMap, it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object.

While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap uses linked list in case of collision and object will be stored in next node of linked list.

Also hashMap stores both key+value tuple in every node of linked list.

What will happen if two different HashMap key objects have same hashcode?

They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap.

In terms of usage HashMap is very versatile and I have mostly used hashMap as cache in electronic trading application I have worked . Since finance domain used Java heavily and due to performance reason we need caching a lot HashMap comes as very handy there.

to check some article on hashMap see here 

 Use of ConcurrentHashMap

 SynchrnozedHashMap and ConcurrentHashMap

Difference between hashtable and hashMap

Read more: http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html#ixzz1yS9tC2fw

Comparable and Comparator example


Comparable

 

/* Source Code- Example */

/* ------------ Sorting thru Comparable Interface (Natural Sorting) ---------
 * Implements mandatory Comparable interface
 */
 class Person implements Comparable<Object>{

String firstname;
 String lastname;
 public Person(String firstname, String lastname) {
 super();
 this.firstname = firstname;
 this.lastname = lastname;
 }

public String getFirstname() {
 return firstname;
 }
 public String getLastname() {
 return lastname;
 }
 /*
 * return -1 : If this object is lesser than the passed object</pre>
<div>        return  0 : If this object is same the passed object
return  1 : If this object is greater than the person */</div>

public int compareTo(Object obj){
 Person person=(Person) obj;
 return this.firstname.compareTo(person.getFirstname());
 }
 }

public class <b>PersonComparable</b> {

public static void main(String[] args) {

List<Person> person=new ArrayList<Person>();

 person.add(new Person("Rajiv","Srivastava"));
 person.add(new Person("Akshay","Kumar"));
 person.add(new Person("Prashant","Gupta"));

/* Sorting- sort method will use compareTo(Object obj) override implementation for natural sorting
 */

Collections.sort(person);

for (Person p:person){
 System.out.println(p.getFirstname()+" "+p.getLastname());
 }
 }
 }
/* Result:

Akshay Kumar
Prashant Gupta
Rajiv Srivastava


*/
/* ———— Sorting thru Comparator Interface (Custom Sorting)
* Implements mandatory Comparator interface
*/

Comparator:


public class <b>MyCustomComparator</b> implements Comparator<Object> {

public int compare(Object obj1, Object obj2){
Empl p1=(Empl) obj1;
Empl p2=(Empl) obj2;

String p1name=p1.getFirstname()+" "+p1.getLastname();
String p2name=p2.getFirstname()+" "+p2.getLastname();

return p1name.compareTo(p2name);
}

public static void main(String[] args) {
List <Empl> plist= new ArrayList<Empl>();

plist.add(new Empl("Arvind","Upadhyay"));
plist.add(new Empl("Arvind","Tendulkar"));
plist.add(new Empl("Arvind","Kejriwal"));

Collections.sort(plist, new MyCustomComparator());

for(Empl p:plist){
System.out.println(p.firstname+ " "+p.getLastname());
}
}

}

class Empl{

String firstname;
String lastname;
public Empl(String firstname, String lastname) {
super();
this.firstname = firstname;
this.lastname = lastname;
}

public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
}

/* Output:
* Arvind Kejriwal
Arvind Tendulkar
Arvind Tripathi */

How to work with Java 6′s NavigableSet and NavigableMap


How to work with Java 6′s NavigableSet and NavigableMap:

This is my first published article on  popular site – mkyong.com

URL-http://www.mkyong.com/java/how-to-work-with-java-6s-navigableset-and-navigablemap/

Also, writing same article on my blog. Hope it will be helpful for you- Rajiv.

You can use latest Java 6′s Collection API to navigate a set and Map collections. These API gives a lot of flexibility to find out required result from the collection.

1. NavigableMap Example

import java.util.NavigableMap;
import java.util.TreeMap;
 
public class NavigableMapDemo {
 
 public static void main(String[] args) {
 
 NavigableMap<String,Integer> navigableMap=new TreeMap<String, Integer>();
 
 navigableMap.put("X", 500);
 navigableMap.put("B", 600);
 navigableMap.put("A", 700);
 navigableMap.put("T", 800);
 navigableMap.put("Y", 900);
 navigableMap.put("Z", 200);
 
 System.out.printf("Descending Set  : %s%n",navigableMap.descendingKeySet());
 
 System.out.printf("Floor Entry  : %s%n",navigableMap.floorEntry("L"));
 
 System.out.printf("First Entry  : %s%n",navigableMap.firstEntry());
 
 System.out.printf("Last Key : %s%n",navigableMap.lastKey());
 
 System.out.printf("First Key : %s%n",navigableMap.firstKey());
 
 System.out.printf("Original Map : %s%n",navigableMap);
 
 System.out.printf("Reverse Map : %s%n",navigableMap.descendingMap());
 
  }
 }

Output

Descending Set  : [Z, Y, X, T, B, A]
Floor Entry  : B=600
First Entry  : A=700
Last Key : Z
First Key : A
Original Map : {A=700, B=600, T=800, X=500, Y=900, Z=200}
Reverse Map : {Z=200, Y=900, X=500, T=800, B=600, A=700}

2. NavigableSet Example

 
import java.util.Arrays;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;
 
public class NavigableSetDemo {
 
  public static void main(String[] args) {
 
 NavigableSet<String> navigableSet = new TreeSet<String>(Arrays.asList(
   "X", "B", "A", "Z", "T"));
 
 Iterator<String> iterator = navigableSet.descendingIterator();
 
 System.out.println("Original Set :");
 while (iterator.hasNext()) {
  System.out.println(iterator.next());
 }
 
 iterator = navigableSet.iterator();
 
 System.out.println("Sorted Navigable Set :");
 
 while (iterator.hasNext()) {
  System.out.println(iterator.next());
 }
 
 System.out.printf("Head Set : %s.%n", navigableSet.headSet("X"));
 
 System.out.printf("Tail Set : %s.%n", navigableSet.tailSet("T", false));
 
 System.out.printf("Sub Set : %s.%n",
   navigableSet.subSet("B", true, "X", true));
 
 System.out.printf("Last Element : %s%n", navigableSet.last());
 
 System.out.printf("First Element : %s%n", navigableSet.first());
 
 System.out.printf("Reverse Set : %s%n", navigableSet.descendingSet());
 
 System.out.printf("Original Set : %s%n", navigableSet);
 
  }
}

Output

Original Set :
Z
X
T
B
A
Sorted Navigable Set :
A
B
T
X
Z
Head Set : [A, B, T].
Tail Set : [X, Z].
Sub Set : [B, T, X].
Last Element : Z
First Element : A
Reverse Set : [Z, X, T, B, A]
Original Set : [A, B, T, X, Z]

Difference between mvc1 and mvc2


n MVC-1 architecture (also referred as Model 1), the request is first handled by a JSP, that interacts with a Bean. Here the JSP page may have partial processing logic, although a bulk of processing logic may be handled by the beans that may interact with the database. The JSP in this case in addition to being responsible for ‘View’ of MVC also takes the resposibility as ‘Controller’, and the beans acting as Model. For small applications that do not have complex processing, this model may be fine, but in case of bigger applications where a lot of processing and decision making is required (Authentication, Logging, Conditional redirection, database interactions, network connections) this is not the best option.

In such cases MVC2 or Model 2 architecture is the better option. It has a Controller Servlet that handles all the incoming requests (You may refer to the Front Controller pattern) and acts as the ‘Controller’, it determines what comes next, a View (JSP) or further processing by Model (Beans doing all the complex tasks), and will decide the view to display the results from the Model.
The links on the JSP pages for next view may also pass through the controller servlet to determine the next view, unlike in MVC-1 where the links on a JSP page will directly point to another JSP page.

Comparable Interface : Problem while adding object to TreeSet


Nice Article:

Comparable Interface : Problem while adding object to TreeSet

</div>
<div id="post-body-2478627897226170008" class="post-body entry-content">
<div dir="ltr">public class X{</div>
<div dir="ltr"></div>
<div dir="ltr">public static void main(String [] arg){
Set s=new TreeSet();
s.add(new Person(20));
s.add(new Person(10));
System.out.println(s);
}
}</div>
<div dir="ltr"></div>
<div dir="ltr">class Person{
int i;
Person(int i){
i = this.i;
}
}</div>
<div dir="ltr">
Can anyone tell me why this code fragment shows me the “ClassCastException”, Using Java 2 1.5 compiler.
In the above code
Set s=new TreeSet();
Set S which is a TreeSet accepts an object that is very true when developer adds an object new Person(20) to code, code will not fail. Now when developer will add another object new Person(10) the code will fail.
Now replace the code with a fresh code
Set s=new TreeSet();
s.add(new Integer(10)); // replace person object with Integer object
s.add(new Integer(20)); // replace person object with Integer object
System.out.println(s);</div>
<div dir="ltr">

The above code will not fail.
Now lets dig in to the concept.
TreeSet is a class belongs to Set interface, being a set it does not accept duplicates. First object insertion goes fine here,Now when we are trying to add the second object then there must be a criteria based on which the 2 object should be comparable. And in the above code there is no such criteria, for uniqueness the set internally use compareable interface to check object equality which is not implemented by the Person class,So in this case developer have to implement the comparable interface in his Person Class.
There are fourteen classes in the Java 2 SDK, version 1.2, that implements the Comparable interface.
BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short, Character, CollationKey, Date, File, ObjectStreamField, String
So when developer will try t add the above objects they won’t give any problem, as developer is facing in above scenario.
Below code for person class will solve the developer’s problem.


public class Person implements Comparable{
int i;
Person(int i){
i = this.i;
}public int compareTo(Object o1) {
if (this.i == ((Person) o1).i)
return 0;
else if ((this.i) > ((Person) o1).i)
return 1;
else
return -1;
}
}