Tuesday 28 February 2012

TreeSet in Java with Examples

In TreeSet the elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
Objects that implement Comparable interface can be used as the element in TreeSet.Use the following constructors for it.
  • public TreeSet()
  • public TreeSet(Collection<? extends E> c)
  • public TreeSet(SortedSet<E> s)
The Comparable interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

You can also create a TreeSet according to the specified comparator.Use the following constructor for it.
  • public TreeSet(Comparator<? super E> comparator)
If the specified comparator is null, the natural ordering of the elements will be used.

Sunday 26 February 2012

Set operations: union, intersection, difference, symmetric difference, is subset, is superset - using TreeSet in Java

The mathematical set operations using Java Collection-Framework  is given below

import java.util.TreeSet;
import java.util.Set;
import java.util.TreeSet;

public class Main {
  public static  Set union(Set setA, Set setB) {
    Set tmp = new TreeSet(setA);
    tmp.addAll(setB);
    return tmp;
  }

  public static  Set intersection(Set setA, Set setB) {
    Set tmp = new TreeSet(setA);
   tmp.retainAll(setB);
    return tmp;
  }

Is StringBuffer really thread-safe ?

May I hope that you have gone through  Difference between StringBuffer and StringBuilder before reading this topic.

All the public methods within StringBuffer are synchronized, which means a method invocation on a StringBuffer instance acts as an atomic operation.i.e.a method execution by one thread can't be interrupted by another thread.

But one point to remember is that,two or more sequential method invocations on a StringBuffer instance by a thread is not synchronized i.e. it is not an atomic operation.

Consider one example

Saturday 25 February 2012

What's the difference between a StringBuffer and StringBuilder?

StringBuffer is in older versions of the Java API and it is thread-safe.String buffers are safe for use by multiple threads. The public methods are synchronized so that each method invocation on a StringBuffer instance acts as an atomic operation.For example two threads can't append one data to a StringBuffer instance at the same time.i.e. one thread can invoke append(String) only after the other thread has returned from the append(String) method.

StringBuilder was introduced in java 1.5.StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized whereas StringBuilder is not synchronized( which implies it isn’t thread safe).

So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.

Wednesday 22 February 2012

Converting from ArrayList to Array & from Array to ArrayList in Java

From ArrayList to Array

Java ArrayList provides two methods to get the array back from your ArrayList.
The methods are given below
  • public Object[] toArray()
  • public Object[] toArray(Object[] a)
Let us see the difference between these two methods

1) public Object[] toArray()

Returns an array containing all of the elements in this collection. If the collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

The returned array will be "safe" in that no references to it are maintained by this collection. (In other words, this method must allocate a new array even if this collection is backed by an array). The caller is thus free to modify the returned array.

This method acts as bridge between array-based and collection-based APIs.

Monday 20 February 2012

ListIterator in Java Collection Framework with Examples

public interface ListIterator
extends Iterator

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). In a list of length n, there are n+1 valid index values, from 0 to n, inclusive.

Note that the remove() and set(Object) methods are not defined in terms of the cursor position; they are defined to operate on the last element returned by a call to next() or previous().

Method Details

1) public boolean hasNext()

Returns true if this list iterator has more elements when traversing the list in the forward direction. (In other words, returns true if next would return an element rather than throwing an exception.)

Sunday 19 February 2012

Iterator Interface in Java Collection Framework

public interface Iterator
An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:
  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved. 

Method Details

1) public boolean hasNext()

Returns true if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing an exception.)

Returns:
true if the iterator has more elements.

2) public Object next()

Returns the next element in the iteration.

Returns:
the next element in the iteration.
Throws:
NoSuchElementException - iteration has no more elements.

3) public void remove()

Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

Difference between fail-fast Iterator vs fail-safe Iterator in Java

Fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun.
The iterators returned by ArrayList's iterator and listIterator methods are fail-fast: if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Implementation of fail-fast Iterators

AbstractList class contains a field protected transient int modCount,stores the number of times this list has been structurally modified. Structural modifications are those that change the size of the list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.
This field is used by the iterator and list iterator implementation returned by the iterator and listIterator methods. If the value of this field changes unexpectedly, the iterator (or list iterator) will throw a ConcurrentModificationException in response to the next, remove, previous, set or add operations. This provides fail-fast behavior, rather than non-deterministic behavior in the face of concurrent modification during iteration.

Saturday 18 February 2012

ArrayList in Java Collections Framework

public class ArrayList
extends AbstractList
implements List, RandomAccess, Cloneable, Serializable
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)
The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

List Interface in Java

The List interface is a member of the Java Collections Framework.It extends Collection interface.
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.
The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods.
The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

Wednesday 15 February 2012

Collection Interface in Java

The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The SDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired. 

Methods of Collection Interface

We will discuss about the following categories of methods that operates on a Collection :

  • Adding and Removing an element
  • Query operations
  • Group Operations
  • Converting from New Collections to Historical Collection 

Adding and Removing an element

Wednesday 8 February 2012

Interfaces and Classes of the Collections Framework

The Collections Framework provides a well-designed set of interfaces and classes for storing and manipulating groups of data as a single unit, a collection. The framework provides a convenient API to many of the abstract data types familiar from computer science data structure curriculum: maps, sets, lists, trees, arrays, hashtables and other collections. Because of their object-oriented design, the Java classes in the Collections Framework encapsulate both the data structures and the algorithms associated with these abstractions. The framework provides a standard programming interface to many of the most common abstractions, without burdening the programmer with too many procedures and interfaces. The operations supported by the collections framework nevertheless permit the programmer to easily define higher level data abstractions, such as stacks, queues, and thread-safe collections.Collections Framework is first introduced with the Java 2 platform, Standard Edition, version 1.2.

Key Interfaces and Classes of the Collections Framework are given below

Tuesday 7 February 2012

Daemon Threads in Java

In java we have two type of Threads : Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). User thread are generally meant to run our program code. JVM doesn't terminates unless all the user thread terminate.

On the other hand we have Daemon threads.Typically these threads are service provider threads. When the thread that created the daemon thread ends, the daemon thread dies with it.This means if the main thread of an application ends and the remaining threads left are Daemon threads, then the JVM will exit killing all the daemon threads without warning.A live daemon thread does not prevent an application from exiting.An application exits when there are no non-daemon threads running.

A daemon thread should be used for some background task that might provide a service to the applications. e.g. a Server thread listening on a port for the clients` requests ,Java Garbage Collector.Garbage collector runs as a daemon thread to reclaim any unused memory. When all user threads terminates, JVM may stop and garbage collector also terminates instantly.

Monday 6 February 2012

Thread Scheduling in Java

We know that threads can run concurrently.Is it really running concurrently ?
Most computer configurations have a single CPU, so threads actually run one at a time in such a way as to provide an illusion of concurrency.Execution of multiple threads on a single CPU, in some order, is called scheduling.Features are

  • The JVM schedules using a preemptive , priority based scheduling algorithm.
  • All Java threads have a priority and the thread with the highest priority is scheduled to run by the JVM.
  • In case two threads have the same priority a time-slicing mechanism is followed.
  • The Java runtime does not implement (and therefore does not guarantee) time-slicing. However, some systems on which you can run Java do support time-slicing. Your Java programs should not rely time-slicing as it may produce different results on different systems. 

Sunday 5 February 2012

ThreadGroup in Java

A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group(i.e. main) has a parent.Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually.


If you not explicitly set the thread group during thread creation, the runtime system puts the new thread in some reasonable default group.

You cannot move a thread to a new group after the thread has been created.  
  
A thread is allowed to access information about its own thread group, but not to access information about its thread group's parent thread group or any other thread groups. 

The Default Thread Group

Deadlock in Java Thread

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Here's an example.
Ramesh and Suresh are employees of a Bank.Before leaving the office ,they have to check each other's work .But one condition is that, both of them can't do the review at the same time.


class Employee {

synchronized void doWork(Employee neighbour) {
System.out.println(Thread.currentThread().getName() + " started work");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ " waiting.... for checking neighbours work");
neighbour.verifyNeighboursWork();
}

Friday 3 February 2012

interrupt() method in Java Thread

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

Interruption is a cooperative mechanism. When one thread interrupts another, the interrupted thread does not necessarily stop what it is doing immediately. Instead, interruption is a way of politely asking another thread to stop what it is doing if it wants to, at its convenience.

A thread sends an interrupt by invoking interrupt() on the Thread object for the thread to be interrupted.(i.e. t.interrupt(); interrupts the thread t). For the interrupt mechanism to work correctly, the interrupted thread must support its own interruption.

public void interrupt() throws SecurityException 

Wednesday 1 February 2012

Life Cycle of a Thread in Java

The following diagram shows the life cycle of a Java Thread. Thread has following states
  • New
  • Runnable
  • Running
  • Sleeping/Blocked/Waiting
  • Dead
These states can be changed to each other as shown in the diagram(NOTE:Please click on the diagram to enlarge it).