"Before software can be reusable it first has to be usable"- Ralph Johnson

Friday, October 10, 2014

How to Stop A Thread in Java

By 9:19 AM
Here is one of the most asked question interviewer asks very often.
How can we stop a thread..??

As we know Thread is one of important Class in Java and multi-threading is most widely used feature, but there is no clear way to stop Thread in Java. Earlier there was a stop method exists in Thread Class but Java deprecated that method citing some safety reason. By default a Thread stops when execution of run() method finish either normally or due to any Exception. In this article we will How to Stop Thread in Java by using a boolean State variable or flag. Using flag to stop Thread is very popular way  of stopping thread and its also safe, because it doesn't do anything special rather than helping run() method to finish it self.
Another important point is that you can not restart a Thread which run() method has finished already , you will get an IllegalStateExceptio, following is a Sample Code for stopping a Thread in Java:


  private class Runner extends Thread{
    boolean bExit = false;
  
    public void exit(boolean bExit){
        this.bExit = bExit;
    }
  
    @Override
    public void run(){
        while(!bExit){
            System.out.println("Thread is running");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(ThreadTester.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
    }
}



Should we make bExit Volatile ?
Since every Thread has its own local memory in Java its good practice to make bExit volatile because we may alter value of bExit from any thread and making it volatile guarantees that Runner will also see any update done before making bExit.

That’s all on how to stop thread in Java , let me know if you find any other way of stopping threads in Java without using deprecated stop() method.
Read More...

Friday, April 27, 2012

How Can We restrict someone to create a limited objects of a class

By 12:05 AM
Here is example how we can restrict someone to create a limited objects of a class :-

class Example{ 
    private static int count; 
    private static int MAX_COUNT = 5; 
    private Example(){ 
    } 
      
    public static Example getObject(){ 
        if(count < MAX_COUNT){ 
              count ++; 
              return new Example
(); 
        } 
        else{
            System.out.println("You exceded the limit");
            //TO DO
        } 
    }
Read More...

Wednesday, February 8, 2012

Top Java Collection Interview Questions

By 8:52 AM
1) What is the Collections API?
A: The Collections API is a set of classes and interfaces that support operations on collections of objects.

2) What is the List interface?
A: The List interface provides support for ordered collections of objects.

3) What is the Vector class?
A: The Vector class provides the capability to implement a growable array of objects.  

4) What is an Iterator interface?
A: The Iterator interface is used to step through the elements of a Collection .

5) Which java.util classes and interfaces support event handling?
A: The EventObject class and the EventListener interface support event processing.

6) What is the GregorianCalendar class?
A: The GregorianCalendar provides support for traditional Western calendars

7) What is the Locale class?
A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region .

8) What is the SimpleTimeZone class?
A: The SimpleTimeZone class provides support for a Gregorian calendar .

9) What is the Map interface?
A: The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

10) What is the highest-level event class of the event-delegation model?
A: The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.

11) What is the Collection interface?
A: The Collection interface provides support for the implementation of a mathematical bag, an unordered collection of objects that may contain duplicates.

12) What is the Set interface?
A: The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

13) What is the typical use of Hashtable?
A: Whenever a program wants to store a key value pair, one can use Hashtable.

14) What is the difference between the size and capacity of a Vector?
A: The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.

15) Can a vector contain heterogenous objects?
A: Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.
Read More...

Important Java Collection Interview Questions & Answers

By 8:36 AM
What is difference between Set and List in Java?
Most of Java programmer knows that Set doesn't allowed duplicate while List does and List maintains insertion order while Set doesn't. What is key here is to show interviewer that you can decide which collection is more suited based on requirements.
 
Difference between HashMap and Hashtable?
HashMap is not synchronized while hashtalbe is not or hashmap is faster than hashtable etc. What could go wrong is that if he placed another followup question like how hashMap works in Java or can you replace Hashtable with ConcurrenthashMap etc. See HashTable vs HashMap in Java for detailed answer of this interview question.
 
What is difference between Synchronized Collection and ConcurrentCollection?
Java5 has added several new ConcurrentCollection classes e.g. ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue etc, which has made Interview questions on Java Collection even trickier. Java Also provided way to get Synchronized copy of collection e.g. ArrayList, HashMap by using Collections.synchronizedMap() Utility function.One Significant difference is that ConccurentCollections has better performance than synchronized Collection because they lock only a portion of Map to achieve concurrency and Synchronization.
 
What is difference between fail-fast and fail-safe Iterators?
Fail-fast Iterators throws ConcurrentModificationException when one Thread is iterating over collection object and other thread structurally modify Collection either by adding, removing or modifying objects on underlying collection. They are called fail-fast because they try to immediately throw Exception when they encounter failure. On the other hand fail-safe Iterators works on copy of collection instead of original collection

What is difference between Iterator and Enumeration?
Iterator duplicate functionality of Enumeration with one addition of remove() method and both provide navigation functionally on objects of Collection.Another difference is that Iterator is more safe than Enumeration and doesn't allow another thread to modify collection object during iteration except remove() method and throws ConcurrentModificaitonException.

When do you use ConcurrentHashMap in Java?
ConcurrentHashMap is better suited for situation where you have multiple readers and one Writer or fewer writers since Map gets locked only during write operation. If you have equaled number of reader and writer than ConcurrentHashMap will perform in line of hashtable or synchronized hashMap.

How do you Sort objects on collection?
Sorting is implemented using Comparable and Comparator in Java and when you call Collections.sort() it gets sorted based on natural order specified in CompareTo method while Collections.sort(Comparator) will sort objects based on compare() method of Comparator.
Read More...

Types of Garbage Collector in Java

By 8:13 AM
Java Runtime(J2SE 5) provides various types of Garbage collection in Java which we can choose based upon our application's performance requirement. J2SE 5 adds three additional garbage collectors except serial garbage collector. Each is generational garbage collector which has been implemented to increase throughput of the application or to reduce garbage collection pause times.
 
1) Throughput Garbage Collector: This garbage collector in Java uses a parallel version of the young generation collector. It is used if the -XX:+UseParallelGC option is passed to the JVM via command line options . The tenured generation collector is same as the serial collector.


2) Concurrent low pause Collector: This Collector is used if the -Xingc or -XX:+UseConcMarkSweepGC is passed on the command line. This is also referred as Concurrent Mark Sweep Garbage collector. The concurrent collector is used to collect the tenured generation and does most of the collection concurrently with the execution of the application. The application is paused for short periods during the collection. A parallel version of the young generation copying collector is sued with the concurrent collector. Concurrent Mark Sweep Garbage collector is most widely used garbage collector in java and it uses algorithm to first mark object which needs to collected when garbage collection triggers.


3) The Incremental (Sometimes called train) low pause collector: This collector is used only if -XX:+UseTrainGC is passed on the command line. This garbage collector has not changed since the java 1.4.2 and is currently not under active development. It will not be supported in future releases so avoid using this and please see 1.4.2 GC Tuning document for information on this collector.


Important point to not is that -XX:+UseParallelGC should not be used with -XX:+UseConcMarkSweepGC. The argument passing in the J2SE platform starting with version 1.4.2 should only allow legal combination of command line options for garbage collector but earlier releases may not find or detect all illegal combination and the results for illegal combination are unpredictable. It’s not recommended to use this garbage collector in java.
Read More...

Monday, November 21, 2011

Deque and ArrayDeque

By 10:55 AM
Deque is the abbreviation of “Double Ended Queue”. A Collection that allows us to add (or) remove elements at both ends. Deque supports total size of collection for both fixed and unspecified size limits.

Deque implementation can be used as Stack(Last in first out ) or Queue(First in First Out). For each insertion, retrieval and removal of elements from deque there exists methods in 2 flavours. One will throw exception if it fails in an operation and another one returns status or special value for each operation.

OperationSpecial value methodException throwing method
Insertion at headofferFirst(e)addFirst(e)
Removal at headpollFirst()removeFirst()
Retrieval at Head
peekFirst()getFirst()
Insertion at TailofferLast(e)addLast(e)
Removal at TailpollLast()removeLast()
Retrieval at Tail
peekLast()getLast()

Implementation of Deque doesn’t require preventing the insertion of null, but when we are using special value method null is return to indicate that collection is empty. So it is recommendable not to allow insertion of null.

ArrayDeque is a class that implements Deque. It has no capacity restrictions. It will perform faster than stack when used as stack and faster than linked list when used as queue. ArrayDeque is not thread Safe. The following example explains how to write program using ArrayDeque.

Example:
import java.util.ArrayDeque;
import java.util.Iterator;


public class DequeExample
{
public static void main(String as[])
{
ArrayDeque adObj = new ArrayDeque(); 


//Insertion by using various methods
adObj.add("Oracle"); 
adObj.addFirst("DB2");
adObj.offerFirst("MySQL");   //returns boolean - true R false 
adObj.offerLast("Postgres");   //returns boolean - true R false

//Retrievals 
System.out.println("Retrieving First Element :" + adObj.peekFirst());
System.out.println("Retrieving Last Element  :"+ adObj.peekLast());


//Removals
System.out.println("Removing First  Element  :"+ adObj.pollFirst());
System.out.println("Removing Last  Element   :"+ adObj.pollLast());


//Reverse traversal
System.out.println("Remaining Elements :");
Iterator it = adObj.descendingIterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}


Output:
Retrieving First Element :MySQL
Retrieving Last Element  :Postgres
Removing First  Element  :MySQL
Removing Last  Element   :Postgres
Remaining Elements :
Oracle
DB2


For more please visit- http://download.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html
Read More...

What's New in Java 6.0 Collection API

By 10:35 AM
Here we have the new Collections APIs introduced in Java 6.0. There are few interesting changes in the Collections APIs, one amoung them is the Deque. Deque is used for the Bi-Directional traversal. It has different implementations including BlockingDeque,ArrayDeque,etc. Let's talk about the Deque and its various implementation, also few more changes in the Collectiona API in Java 6.0

Following are the new collection APIs introduced in Java 6.0. And the list of Interfaces and classes are given below.


New Interfaces:

  • Deque
  • BlockingDeque
  • NavigableSet
  • NavigableMap

New Classes:

  • ArrayDeque
  • LinkedBlockingDeque
  • ConcurrentSkipListSet
  • ConcurrentSkipListMap
  • AbstractMap.SimpleEntry
  • AbstractMap.SimpleImmutableEntry
And following are the updated Classes in Java 6.0
  • LinkedList
  • TreeSet
  • TreeMap
  • Collections
Read More...