Home » Core Java

Category Archives: Core Java

Advertisements

readObject() and writeObject() &nd; readResolve()

There is, however, a strange yet crafty solution. By using a built-in feature of the serialization mechanism, developers can enhance the normal process by providing two methods inside their class files. Those methods are:

  • private void writeObject(ObjectOutputStream out) throws IOException;
  • private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

Notice that both methods are (and must be) declared private, proving that neither method is inherited and overridden or overloaded. The trick here is that the virtual machine will automatically check to see if either method is declared during the corresponding method call. The virtual machine can call private methods of your class whenever it wants but no other objects can. Thus, the integrity of the class is maintained and the serialization protocol can continue to work as normal. The serialization protocol is always used the same way, by calling either ObjectOutputStream.writeObject() or ObjectInputStream.readObject(). So, even though those specialized private methods are provided, the object serialization works the same way as far as any calling object is concerned.

ref:http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html

readResolve is called after readObject has returned (conversely writeReplace is called before writeObject and probably on a different object). The object the method returns replaces this object returned to the user of ObjectInputStream.readObject and any further back references to the object in the stream. It is mostly used for serial proxies for example in case is Singleton class if it is serializable then we need to specify in readResolve that it returns singleton object and not the one which is read from persisted location.

Advertisements

Producer Consumer Problem Solution Example in Java

This is a simple example of Producer and Consumer problem, where Producer created and puts data in a shared list but waits if the list is full. Similarly Consumer consumes data from the list but waits if the list is empty


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

class Pool{
	List list = new ArrayList();
	int MaxSize= 5;

	synchronized String getData() throws InterruptedException{
		if(list.isEmpty()){
			System.out.println("Get Data List is empty, wait please");
			wait();
			return null;
		}
		System.out.println("Get Data done: " + list.get(0));
		notifyAll();
		return list.remove(0); 
	}

	synchronized boolean setData(String str) throws InterruptedException{
		if(list.size()>=MaxSize){
			this.wait();
			System.out.println("Set Data , List is full please wait");
			return false;
		}else{
			System.out.println("Set Data , Data added > " + str);
		}
		list.add(str);
		notifyAll();
		return true;
	}

}
class Producer extends Thread{
	Pool pool;
	Producer(Pool pool){
		this.pool = pool;
	}

	@Override
	public void run() {
		for(int i=1; i<=70; i++){
			try {
				if(!this.pool.setData(i+"")){
					i--;
				}
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

}

class Consumer extends Thread{
	Pool pool;
	Consumer(Pool pool){
		this.pool = pool;
	}
	@Override
	public void run() {
		while(true){
			String i;
			try {
				i = this.pool.getData();
				Thread.sleep(2000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}
}

public class ProducerConsumerTest {
	public static void main(String[] args){
			Pool pool = new Pool();
			Producer pro = new Producer(pool);
			Consumer con = new Consumer(pool);
			pro.start();
			con.start();
	}
}

Java Concurrency in Practice

Concurrent programming covers concept of parallel program execution, inter process or thread communication, shared object , thread executor frame work, future and callable objects etc.

In this article we would cover following concepts :

  1. What is concurrency
  2. Process and Threads
  3. Thread communication
  4. Synchronization and Locking
  5. Atomic variable, Volatile variable and Semaphores
  6. Immutable objects
  7. High level of concurrency
  8. Executor framework
  9. Future and Callable objects
  10. Concurrent Collection

1: What is Concurrency: Concurrency means ability to run various part of a program parallely. Classic example is your mobile phone where you can talk while while accessing net and your phone pops out any live notifications without waiting any process to complete. So in other words these set of process are running parallel and this is called concurrency.

Java Provides set of APIs to write concurrent programming application that we would cover in this article.

2: Process and Threads: Java Process are same as any other operating system process, they have their own memory allocation and own set of resources. This is a simple example to show how can you create a process using Java API to invoke any OS level command.


public static void main(String[] args){
		try {
			Process p = new ProcessBuilder("ls", "-l").start();
			BufferedInputStream bin = new BufferedInputStream(p.getInputStream());
			InputStreamReader inReader = new InputStreamReader(bin);
			BufferedReader reader = new BufferedReader(inReader);
			String line;
			while((line = reader.readLine())!=null){
				System.out.println(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

Threads on the other hand are light weight processes which are created from a single parent process. Threads can share all resources belong to its parent thread or process and they occupy less memory with respect to the process.

Java API provides two ways to create threads

  • Implementing Runnable Interface
  • Extending Thread Class

We all know about them so I am not going in deep of them.

3: Thread Communication: Thread communication means all possible ways by which threads can send signals to each other and do some work in specified or synchronized manner. For example suppose there are some Producers and Consumers for some goods for a particular Store. So here Producer can produce so item only if store is not FULL otherwise Producer would wait till Consumer consumes some of the products . Same way for Consumer they can consume only if  that Store is not empty or else they would have to wait till a Producer produces some products.

Some common ways of thread communications are described here:

-Thread.sleep(milliseconds) This way is not very efficient but still a possible way where you put a Thread in sleep based on some condition. This would invoke the thread after specified time and check again if the condition is satisfied or not.    ex:   if(condition) then Thread.sleep(millisecond);

-Wait/Notify/Notify All: A Thread  can invoke Object.wait() method if any condition is not satisfied and this would put that thread in wait condition. When some other Second thread invokes Notify or Notify All then previous thread/s would be notified, here this second thread might change the conditional state which would enable previous thread to resume their execution once they are notified.

-CountDownLatch/CyclicBarrier: A Synchronization technique which allows one or more thread to wait until some specified no of tasks are performed by another thread.

CountDownLatch signal = new CountDownLatch(N);

CountDownLatch is initialized with some counter value. A thread which invokes signal.await(); get blocks until current count reaches zero by some other thread by calling signal.countDown()

-Semaphore: It also little bit similar concept as CountDownLatch but rather storing any counter value a semaphore maintain set of permits (like tokens). A thread has to acquire a permit before executing some exclusive section and after its execution is complete it has to release the permit. This approach is useful in cases where there are fixed no of worker threads has to work on a task.

Semaphore available = new Semaphore(MAX_AVAILABLE, true);

A semaphore which is initialized with value one can serve for mutual exclusion execution where at a time only one thread can enter the execution after accruing the required permit from semaphore.

4: Synchronization and Locking : When multiple thread are accessing a shared resource then in order to maintain its data integrity it is necessary that at a time only one thread is accessing or updating the resource. There are two ways of basic synchronization which are  achieved with the help of intrinsic Lock associated an Object.

Method Synchronization: We can make whole method synchronized and the running thread would take lock on the object which owns that method.

public synchronized int getCounter (int value) {
//method code
}

Synchronized Block : If we don’t want to make whole method as synchronized then we can put the set of statements in synchronized block which we want to be executed by single thread a time. Not to mention that we should prefer synchronized block over method as they reduces size of synchronized code. Unnecessary synchronized code is always a processing overhead so keep it minimal.

synchronized(Object) {
// statements to be synchronized
}

5: Atomic variable, Volatile variable and Semaphores: 

Atomic variables:  Java has provided set of classes in java.util.concurrent.atomic package, these classes have get and set methods which works like reading and writing on Volatile variables. Basically they ensure that all update operations should work in atomic manner even if they are not put in manual synchronized.

Volatile variable: If a thread access some variable usually they keep them in their local cache. But if want to enforce that thread should always read that variable from main memory whenever they access then we can mark it as volatile.

private volatile int counter;

Java 5 guarantees that write(update) to any volatile variable happens before any concurrent read. This becomes very important where all reader threads do not acquire any locking and until writer thread comes out of the synchronization block they can still use old value.  Note: Volatile can not be used with classes or methods so they are not the replacement of synchronized section.

Semaphore: It also little bit similar concept as CountDownLatch but rather storing any counter value a semaphore maintain set of permits (like tokens). A thread has to acquire a permit before executing some exclusive section and after that it has to release the permit. We have explained in detail in Inter Thread Communication Section.

6: Immutable objects: In some cases we my not want to allow to change the state of the object once it created example String class is immutable class. Immutable objects can not be modified so they are automatically thread safe in con current execution.

Read more about immutable class in my another section :Guidelines to write immutable classes.

=====================================================================================

7: High level of concurrency: Java 5 onward version has very good built in APIs to support advance level of concurrency. High level concurrency provides following components :

-Locks: java.util.concurrent.locks.*  package. So far we have used Java implicit lock which is simple to use but has some limitations. Java concurrent Locking API provides more versatile Lock interface and its implementations ReadWriteLock , RenterantLock which also works like implicit Object Lock. We would cover it in detail in my another article. Here is small code to using Lock Api.


       //Creating Lock object 
       private final Lock lock = new ReentrantLock();
       Boolean myLock = false;
       //accruing the lock
       myLock = lock.tryLock();
       //releasing the lock
       lock.unlock();

-Executors:  So far Threads were sufficient for simple applications for concurrent programming. In highly complex and lag application it is difficult and complex to do thread management by ourselves. Java API 5 onward has built in framework  to create , maintain the set of threads and their life cycle. Our job is to provide them a Runnable worker Object for business processing.

Executor Interface: java.util.concurrent package has defined three executor interfaces. Executor provides simple method e.execute() which is equivalent to new Thread(runnable).start() call.

1:Executor interface support launching of new tasks by its execute method.

2:ExeutorService, sub interface of executor which can manage life cycle of both task and executor. It supplements execute method with similar submit method: <T> Future submit(Runnable task, T result). Here return types Futures object’t get method would return the result on successful execution.

3:ScheduledExecutor is sub interface of ExecutorService which additionally allows to run a callable or runnable object after specified delay or periodically.

ThreadPool: Most of the executor implementation use ThreadPool which consist of number of worker thread which can execute a runnable task. This reduces the overhead of thread creation and thread life cycle management in large application.

Example:

 
         public static void main(String[] args) {
          //Specify a RejectedExecutionHandler to handle the task in case they are rejected by thread pool when Queue is also fulled.
          RejectedExecutionHandler rejHandler = new PoolRejectHandler();
          // specify default size of ThreadPool
          int coreSize=10;
          // specify maximum size of Thread Pool
          int maxSize = 50;
          int keepAliveTime = 900;
          // specify the Queue to hold runnable objects while no of threads exceeds to Default Pool Size
          BlockingQueue queue = new LinkedBlockingDeque(200);
          ThreadPoolExecutor pool = new ThreadPoolExecutor(coreSize, maxSize, keepAliveTime, TimeUnit.MILLISECONDS,
 queue, rejHandler);
          Runnable worker = new Worker();
          //execute the runnable task
          pool.execute(worker);
          }

-Future and Callable Objects: Future Interface represents the result of an asynchronous call. It provides methods to check if the computation is complete, to wait for its completion or to retrieve the result of the computation. This is the object which is return by the ExecutorService submit method, it can be used for doing post processing once thread’s execution is over.

Callable:A task that returns a result and may throw an exception. Implements define a single method with no arguments called call. This is a supplement to Runnable and can be passed in Executor.submit() method.

10: Concurrent Collections: JAVA API has given several ready to use concurrent collection in java.util.concuttent package. These collections can be categorized by thee main interface they implement .

BlockingQueue: It is sub interface of Queue and in addition it provides get() and put() . get() method would wait of the queue is empty and put method would wait if the queue is full. Hence no need to put additional monitors wile working with multiple threads. LinkedBloackingQueue and ArrayBlocking Queue are popular implementation of this.

ConcurrentMAP: This is sub interface of java.util.Map, that defines useful Atomic operation. That means remove or replace key value only if key-value is present or add key-value only if key is absent. Making these operations atomic in nature helps to avoid need of synchronization.   Popular implementation of ConcurrentMap is Concurrent HashMap.

-ConcurrentNavigableMap: This is third interface provided in Concurrent package how ever this is not very much popular as above two interfaces. This supports approximate match and its popular implementation is ConcurrentSkipListMap

 

Why Object class clone method is protected.

This is one of the tricky but frequently asked question.

Objects class’s clone method is protected and by default clone method is not visible and not available outside the class, there must be some reason behind this design. The reason is before making clone method available to use; a class has to implement  Cloneable interface first and override its clone method and then it is the responsibility of the class to expose this method through any other public method or by making the @Overriden clone method itself public.

SALLOW or DEEP Cloning?

Object class provide implementation of clone method and by default it provides SHALLOW  cloning , it simply creates a new instance and simply copies all the fields into new instance.  Standard way of providing Shallow cloning is to call super.clone() from the overridden clone method, that’s all it will do the job for you. Note all primitive data would get copy but  if there are any object   fields in your class then only their reference would be copied to the cloned object .


@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}

If you want to deep cloning in that case you need to override  the clone  method  and need to  give your own implementation of clone. Rather calling super.clone you  have to copy all NON MUTABLE  fields explicitly.

Typical example here you can see class Person contains object of class Mobile which further hold a Map collection. While doing Deep cloning of Person class we need to explicitly tell clone method to create new objects for its MUATBLE fields: Student and phonebook MAP. So we can not pass their reference during DEEP cloning.

//Deep Cloning Example
class Mobile{
	int mobileNo;
	Map<String, Integer> phoneBook;
	Mobile(int mobileNo,Map<String, Integer> phoneBook ){
		this.mobileNo=mobileNo;
		this.phoneBook=phoneBook;
	}

}
class Person{
	int age;
	String name;
	Mobile mobile;
	public Person(int age, String name, Mobile mobile) {
		super();
		this.age = age;
		this.name = name;
		this.mobile = mobile;
		System.out.println("Constrct call P1");
	}

//	@Override
//	public Object clone() throws CloneNotSupportedException {
//		return super.clone();
//	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		Map<String, Integer> newphoneBook = new HashMap<String, Integer>();
		//copy content of phoneBook
		for(String key : this.mobile.phoneBook.keySet() ){
			newphoneBook.put(key, this.mobile.phoneBook.get(key).intValue());
		}
		//create new mobile object with copied value of phone book
		Mobile mobile = new Mobile(this.mobile.mobileNo, this.mobile.phoneBook);
		//create new instance of person and copy these new field values
		return new Person(this.age, this.name, this.mobile);
	}

}

What is the purpose of calling Super.clone() from clone method?

By convention, the returned object should be obtained by calling super.clone. If a class and all of its superclasses (except Object) obey this convention, it will be the case thatx.clone().getClass() == x.getClass(). This way you do not need to implement clone method for shallow cloning.

By convention, the object returned by this method should be independent of this object (which is being cloned). To achieve this independence, it may be necessary to modify one or more fields of the object returned by super.clone before returning it. Typically, this means copying any mutable objects that comprise the internal “deep structure” of the object being cloned and replacing the references to these objects with references to the copies. If a class contains only primitive fields or references to immutable objects, then it is usually the case that no fields in the object returned by super.cloneneed to be modified.

The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a “shallow copy” of this object, not a “deep copy” operation.

Ref:http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#clone()

Simple Combination Generation Algorithm.

Some times we come across situation of generating all possible combinations of given set of values or objects. One classical example of combination without repetition is Lottery System where lotteries are listed for all possible number combination but the one lucky combination wins that.

Another example of combination is number lock where we set a number combination as a key.Whichever be the need below is a simple algorithm of creating combination.

Combination means all possible arrangements of given set of values or objects.

Combinations2

Suppose we have been given set of some words or numbers or say letters like {a,b,c,d}. Then think how do we practically crate a combination.. Answere is you would probably pick an item say a

a,,,,

then you may place another item in the available space ex:

a,,b,

then you would put c and d.

a,c,b,

and then

a,c,b,d

This is how you have achieved one combination where we put first element ‘a’ at first position and arranged other three elements at vacant positions one by one. Like wise in next iteration we can place a at second positions and again place all element one by one in vacant positions.

We have mode this practical approach in algorithm where we pick first item and put in all possible positions and then pick second element and put in all possible positions.

We are using approach or recursion where we first position first element ‘a’ in all available possible position one by one in a loop and then we call subsequently same approach for other elements one by one. Simple here you go !

Here is a simple code written for this algorithm.



import java.util.Arrays;
public class PasswordGen {
static String[] options = {"a","b","c","d"};
static String[] places = new String[options.length];
static int count;

public static void main(String [] args){
  //Starting with initial position of a i.e. 0
  sequence(0,places.clone());
}

private static void sequence(int level, String[] holder){
  if(level>=options.length){
    //combination complete
    System.out.println(""+(++count) + " Combination " + Arrays.toString(holder));
    return ;
  }

  String val = options[level];
  String[] inrHolder = null;
  for(int c=0; c<holder.length; c++){
    inrHolder = holder.clone();
    if(inrHolder[c]==null){
      inrHolder[c]=val;
      sequence(level+1, inrHolder.clone());
    }
  }
  return ;
}
}



Output of the above program tested for sample a,b,c,d :

1 Combination [a, b, c, d]
2 Combination [a, b, d, c]
3 Combination [a, c, b, d]
4 Combination [a, d, b, c]
5 Combination [a, c, d, b]
6 Combination [a, d, c, b]
7 Combination [b, a, c, d]
8 Combination [b, a, d, c]
9 Combination [c, a, b, d]
10 Combination [d, a, b, c]
11 Combination [c, a, d, b]
12 Combination [d, a, c, b]
13 Combination [b, c, a, d]
14 Combination [b, d, a, c]
15 Combination [c, b, a, d]
16 Combination [d, b, a, c]
17 Combination [c, d, a, b]
18 Combination [d, c, a, b]
19 Combination [b, c, d, a]
20 Combination [b, d, c, a]
21 Combination [c, b, d, a]
22 Combination [d, b, c, a]
23 Combination [c, d, b, a]
24 Combination [d, c, b, a]

Key notes of Singleton Pattern

Singleton has been one of the most discussed pattern in interviews. These are some key points while writing singleton pattern.

  • Only one object instance is required.
  • Synchronization of getInstance() or only critical section: It is recommended to keep only object creation part in synchronised section to reduce the overhead as it is costly.
  • Lazy or early initialisation: Well if you need object should only be initialized when first time getInstance method is called, this is called lazy initialisation. If object is required to be preloaded then we can use a static block to load the instantiate.
        static{
           SimpleSingleton.getInstance();
         }
  • DoubleCheck : This is a mechanism to ensure only one object is created while calling getInstance method
    public static SimpleSingleton getInstance(){
    		//double null check
    		if(_INSTANCE==null){
    			synchronized(SimpleSingleton.class){
    				_INSTANCE = new SimpleSingleton();
    			}
    			System.out.println("Object created");
    		}
    		return _INSTANCE;
    	}
  • How to prevent cloning: If singleton class is not extending any class then if you do not implement cone method; that is enough to prevent cloning of object of singleton class. If Singleton class is extending any class then optionally you can override its clone() method and you can throw CloneNotSupported exception out of that.
  • Ensure Object is not serializable. As we know that Deserialization can bypass the constructor call and object can be instantiated (Only if class implements Serialization interface). So if we are giving an option to serialize a singleton object then we need to enforce not to read stream object. readResolve method is called when ObjectInputStream has read an object from the stream and is preparing to return it to the caller. ObjectInputStream checks whether the class of the object defines the readResolve method. If the method is defined, the readResolve method is called to allow the object in the stream to designate the object to be returned. The object returned should be of a type that is compatible with all uses. If it is not compatible, a ClassCastException will be thrown when the type mismatch is discovered.
            public Object readResolve(){
    		return getInstance();
    	}
  • Using Static Inner class in Singleton pattern: Technically it would be treated by a thread as happens before relationship  which you can say as thread safe approach. But the same thing can be done by a static block with pre initialization of singleton object.
    public class Singleton  {
           public static final Singleton _INSTANCE ;
           //1: Simple way of getting object 
           public static Singleton getInstance() {
              if (null == _INSTANCE) {
                    _INSTANCE = new Singleton();
              }
              return _INSTANCE;
           }
           
           //2: using Static inner class approach
           static Singleton getInstance(){
              return SingletonHolder._INSTANCE;
           }
           static class SingletonHolder{
    	   private static final Singleton _INSTANCE = new Singleton();
           } 
           
           //3: using static block pre initialization approach
           static {
             _INSTANCE = new Singleton();
           } 
           or 
           public static final Singleton _INSTANCE = new Singleton();
          }
  • Making Singleton object Immutable:

Java Collection API -Part 2 (Map)

In continuation of first part of introduction to Java Collection API Part 1, now we would be covering the other part and that is Map api. MAP is designed to store Key-Value pair combination as we know. Some distinct features of MAP are

  • Key can not be repeated
  • Key can be mapped to only one value
  • It depicts mathematical function F(x) -> y , where x represents key and y is the value
  • Basic operations provided by map : get, put , containsKey, containsValue , empty , size
  • Map provides collections views to iterate over the values it holds
    • ketSet      : Set of keys
    • value        : Collection os values, it is not a set as multiple keys can point to same values
    • entrySet  : Map internally contains the set of key-value pair which is represented my inner interface Map.Entry
  • These collections views are good for iteration , modification , removal but CAN NOT BE USED For ADDITION
  • Java API has provided three implementation of MAP interface: HashMap, HashTable, LinkedHashMap
  • MAP also has another sub interface SortedMap which is implemented  by TreeMap
JAVA MAP Api

JAVA MAP Api

1: HashMap: HashMap is most basic implementation of MAP interface

2: HashTable : Similar to HashMap
-Thread safe and synchronized

3: LinkedHashMap : Values are placed internally as likened list
-Ordered

4: TreeSet : Values are placed in sorted manner. Natural sort of Comparable/Comparator logic is used. It is the similar collection as TreeSet but here Key’s are compared and sorted while putting values in MAP.

Java Collection API -Part 1 (Set , List, Queue)

Java has defined main interface Collection from where all collection APIs are inherited. MAP is another interface which is also another very imported interface which I have covered in my another post Java Collection API Part-2

Collection Interface is subclasses into three another Interfaces:  Set, List and Queue. hierarchy is displayed in below image:

JavaCollection1

Collection interface provides abstract of following basic operations

  • add(E element)
  • addAll(Collection c)
  • contains(Object e)
  • size()
  • isEmpty()
  • remove(Object o)
    etc.

In addition to these basic set of operations Specialised collection APIs further add their unique behaviours. Lets see in detail.

1: SET (Interface)
Set Interface is subclass of collection and it is designed to hold Unique values as it is inspired from mathematical set.
-No duplicate values.
-Not indexed

Specialised Implementation of SET
1.1: HashSet class ==>Set, is the basic implantation of Set.
Set is basically good option when you want to count Unique values. Ex Set set = new HashSet(Collection c);

1.2: Linked HashSet class ==> Set is set implantation where internally it maintains linked list where inserted values are also preserved with their order of insertion.

1.3: SortedSet (I) ==> Set it is designed to keep items in sorted values

1.4 TreeSet class==> SortedSet, in sorted set elements are placed in ascending ordered. Elements object class has to define the comparison logic with comparable or comparator.

2: LIST (Interface)
List is an ORDERED collection and can contain DUPLICATE values.
-Duplicate Yes
-Indexed Yes

Some additional methods exposed from List
-add(int index, Object obj)
-set(int index, Object obj)
-addAll(int index, Collection c )  etc

Specialised Implementation of LIST
2.1 ArrayList class ==> List this is a basic implementation of list which dynamically grows its size. You can also specify its initial capacity at the time of creation also.

2.2 Vector class ==>List similar to arraylist but all method are synchronized.
-Threadsafe

2.3 Linked List class==> List , Dqueue, Cloneable, Serializable
in addition to list it provides all basic operation get, insert, remove from front and back both side. Its Doubly linked List

-addFirst(Object o)
-addLast(Object o)
-getFirst()
-getLast()
-removeFirst()
-removeLast()

3: Queue (Interface)
Queue is another direct sub interface of Collection which is designed to hold temporarily objects before they get processed. Queue has some additional methods for basic operation
Queue Interface Structure

Queue Interface Structure
Type of Operation Throws exception Returns special value
Insert add(e) offer(e)
Remove remove() poll()
Examine element() peek()

Some major Specialisation of Queue
3.1 DQueue (I) ==> Queue
DQueue is similar to queue but offers all basic operation’s like insert, remove, get from Front and rear both ends.
Front(First)-> [][][][][][] ->Rear(Last)
So operation for add and remove wold be like:
Add: addFisrt, addLast, offerFirst, offerLast
Delete: removeFirst, removeLast, poolFirst, poolLast

3.2 Blocking Queue (I) ==> Queue
Blocking is a Queue that additianaly supports operations that wait for queue to get emplty while adding values or will wait for queue to become non empty while fetching some values.

Throws exception Special value Blocks Times out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicable not applicable

Ref:http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html

3.3 PriorityQueue Class ==> Queue
Unbounded queue based on proprity heap, Elements are ordered on natuarl order or based on the Comparator provided in Queue constructor.

3.4 LinkedBlocking Queue Class ==> BlockingQueue, Serialisable ++
Optianally bounded queue based on linked nodes which follows FIFO pattern.

==============================

Some of the common good practices I am trying to post here, in case if you some other better practices I would be glad if you can share here by your comments.

  1. Use Iterator or Advance For loop: 

Consider below code

               for(Person p : pList){
			System.out.println("Person Name: " + p.name);
			if(p.id==11){
				pList.remove(p);
			}
		}

This is not the correct way of modifying the collection, this would give java.util.ConcurrentModificationException since you are trying to modify the collection while iterating over it. Safe way to modify the collection is by using Iterator. Please note even in case of Iterator also it can throw this exception if the collection is modified out side this iteration.

Rehashing in Java HashMap and Race condition

Hashing – ReHashing and Race condition
Basically while creating a hash map collection assign it a default size (of 10). Later stage when elements are added in the map and after certain stage when you come close to your initial defined capacity there is requirement of ReHashing to retain the performance.

There is LoadFactor defined for the collection (said to be good as .75) and this specifies the good index for time and space.
LARGER load factor => lower space consumption but higher lookups
SMALLER Load factor => Larger space consumption compare to the required no of elements.
Java specification suggests that Good loadfactor value is .75

Hence Suppose you have maximum requirement to store 10 elements in hash then considering the Good Loadfactor .75 = Rehashing would occur after adding 7 elements in the collection. In case if your requirement in this case would not accede to 7 then Rehashing would never occur.

If there are really large no of elements going to be stored in the hashmap then it is always good to create HashMap with sufficient capacity; this is more efficient than letting it to perform automatic rehashing.

RACE condition : While doing the rehasing internal elements which are stored in a linked list for given bucket. They get reverse in the order. Suppose there are two threads encounter the race condition in same time then there are chances of second therad can go in infinite loop while traversal since the order has been changed.

Reference : http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html