Sunday, 26 September 2010

Inner classes in java

In Java it is possible to define one class inside another. A class defined inside another one is called an inner class . Java provides two kinds of inner classes--static and non-static.

Thursday, 23 September 2010

blocking queue has the following characteristics:
  • methods to add an item to the queue, waiting for space to become available in the queue if necessary;
  • corresponding methods that take an item from the queue, waiting for an item to put in the queue if it is empty;
  • optional time limits and interruptibility on the latter calls;
  • efficient thread-safety: blocking queues are specifically designed to have their put() method called from one thread and the take() method from another— in particular, items posted to the queue will be published correctly to any other thread taking the item from the queue again; significantly, the implementations generally achieve this without locking the entire queue, making them highly concurrent components;
  • integration with Java thread pools: a flavour of blocking queue can be passed into the constructor of ThreadPoolExecutor to customise the behaviour of the thread pool.
These features make BlockingQueues useful for cases such as the following:
  • a server, where incoming connections are placed on a queue, and a pool of threads picks them up as those threads become free;
  • in a variety of parallel processes, where we want to manage or limit resource usage at different stages of the process.

Queues in Java 5: the Queue interface

Java 5 adds queues to the Collections framework. A queue is in some ways a sub-construct of a list, usually implemented as a linked list, with the following characteristics:
  • unlike a normal list, it is not random access: that is, you can't get or set the element at an arbitrary position in the list;
  • get and set operations always take place at the ends of the queue (generally, one "takes from the head" and "puts on the tail").
In a standard queue, the next item to be taken is the one at the head of the queue, i.e. the one that has been there the longest. When items are added to the queue, they are added to the tail. The item at the tail can only be accessed once all the items placed before it have been removed in order.

Why use a queue?

So you may well be thinking: why use a queue if it has these restrictions? Can't you just use a boring old ArrayList or LinkedList1? It turns out there are at least three main reasons:
  • in some cases, a queue is "conceptually what we want";
  • eliminating random access allows optimisations for concurrency;
  • Java's efficient BlockingQueue implementations can take some of the work out of the most typical use of queues.
Places where we "conceptually" want a queue are where we are dealing with a so-called producer-consumer pattern. That is, one thread "produces" a list of jobs for another thread to pick up. Of course, we could use an ordinary (synchronized) LinkedList if this was purely our motivation. However, it turns out that restricting access to the head and tail of the queue allows for further optimisation for concurrent access.

Queues with thread pools

One place, then, in which queues are useful is for the work queue of a thread pool. Java provides the ThreadPoolExecutor class; when constructing this class, you can pass in the queue that you want the thread pool to use. Or, you can construct your thread pool with one of the utility methods in the Executors class, in which case a default BlockingQueue will be used.

Queue implementations firstly share a new Queue interface, which has several methods for accessing the head and tail of the queue. Recall that items are always placed on the end or "tail" of the list, and always read from the beginning or "head" of the list.
OperationThrows exception
if not possible
Returns value
if not possible
Add item to tailadd()offer()
Remove item from headremove()poll()
"Peek" item at headelement()peek()
Methods specified by the Java Queue interface

Types of Queues

Java provides Queue implementations depending on a few key criteria:
  • thread-safety: if you don't require the queue to be accessed concurrently from multiple threads, then a plain LinkedList can be used as a Queue; the advantage of the other implementations is that they offer efficient thread-safety;
  • blocking or non-blocking: various blocking implementations add extra methods to put and remove items from the queue, blocking until the operation is possible, with an optional time limit;
  • bound or non-bound: sometimes it is useful to put an upper limit on the number of items that can fit in the queue, e.g. to prevent a thread pool from queueing up too many jobs when the machine is busy;
  • other special operations: Java provides an implementation that orders by priority, and another that applies a delay to queued items.
As of Java 6, the various queue classes are as follows:
Queue implementations as of Java 6
Blocking?Other criteriaBoundNon-bound
BlockingNoneArrayBlockingQueueLinkedBlockingQueue
Priority-based PriorityBlockingQueue
Delayed DelayQueue
Non-blockingThread-safe ConcurrentLinkedQueue
Non thread-safe LinkedList
Non thread-safe, priority-based PriorityQueue
One further type of queue not included above is the SynchronousQueue, which is effectively a zero-length queue (so that a thread adding an item to the queue will block until another thread removes the item).

Blocking queues

In general, the most interesting queue implementations are the various blocking queues, which allow efficient concurrent access and are useful for coordinating objects between threads, particularly in the so-called producer-consumer pattern. In Java, all blocking queue implementations implement the BlockingQueue interface, which we look at next.

Tuesday, 21 September 2010

java.math.BigInteger

Unbounded range. To work with integers that are larger than 64 bits (the size of a long), use java.math.BigInteger. This class represents unbounded integers and provides a number of methods for doing arithmetic with them.
Overflow in standard arithmetic. The problem with arithmetic using ints (or longs) is that, if the value becomes too large, Java saves only the low order 32 (64 for longs) bits and throws the rest away. For example, we can use the maximum value that can be stored in an int as an example. Both of the following operations can't possibly fit into an int, but the arithmetic doesn't produce an error, it produces a result!

import java.math.BigInteger;

public class TestOverflow {
public static void main(String[] args) {
int bad = 2000000000; //Close to int max value.
System.out.println("bad = " + bad);
System.out.println("bad + 1 = " + (bad + 1));
System.out.println("bad * 3 = " + (bad * 3));
System.out.println("bad * 4 = " + (bad * 4));

BigInteger good = BigInteger.valueOf(2000000000);
System.out.println();
System.out.println("good = " + good);
System.out.println("good.add(BigInteger.ONE) = " + good.add(BigInteger.ONE));
System.out.println("good.multiply(BigInteger.valueOf(3)) = " + good.multiply(BigInteger.valueOf(3)));
System.out.println("good.multiply(BigInteger.valueOf(4)) = " + good.multiply(BigInteger.valueOf(4)));
}
} 
 
Produces this output. If a result exceeds Integer.MAX_VALUE (2,147,483,647), the result will be wrong, but Java doesn't report an error! The BigInteger results are correct. But you do have to put up was some seriously ugly syntax.
bad = 2000000000 bad + 1 = 2000000001 bad * 3 = 1705032704 // Smaller? bad * 4 = -589934592 // Negative?!!! Overflowed into sign bit. good = 2000000000 good.add(BigInteger.ONE) = 2000000001 good.multiply(BigInteger.valueOf(3)) = 6000000000 good.multiply(BigInteger.valueOf(4)) = 8000000000 Omitted features. BigInteger methods ignored in this summary: bit operations, random numbers, and prime testing.

Constructors and Methods

Assume
BigInteger bi, bi1, bi2, bi3, bi4;
BigInteger[] bia; // array holding division result and remainder.
String s; int i; long lng; float f; double d;
Constructors, constants, and static factory methods
bi = new BigInteger(s);Create BigInteger with decimal value represented by decimal String s.
bi = BigInteger.ONE;Predefined value 1.
bi = BigInteger.ZERO;Predefined value 0.
bi = BigInteger.valueOf(lng);Use this factory method to create BigIntegers from numeric expressions. An int parameter will be automatically promoted to long.
Arithmetic operations
bi1 = bi2.abs();Returns BigInteger absolute value.
bi1 = bi2.add(bi3);Returns sum of bi2 and bi3.
bi1 = bi2.divide(bi3);Returns division of bi2 and bi3.
bia = bi2.divideAndRemainder(bi3);Returns array of two BigIntegers representing the result of division and remainder of bi2 and bi3.
bi1 = bi2.gcd(bi3);Returns greatest common divisor of bi2 and bi3.
bi1 = bi2.max(bi3);Returns maximum of bi2 and bi3.
bi1 = bi2.min(bi3);Returns minimum of bi2 and bi3
bi1 = bi2.mod(bi3);Returns remainder after dividing bi2 by bi3
bi1 = bi2.multiply(bi3);Returns product of bi2 and bi3.
bi1 = bi2.pow(bi3);Returns bi2 to the bi3 power.
bi1 = bi2.remainder(bi3);Returns remainder of dividing bi2 by bi3. May be negative.
i = bi.signum();-1 for neg numbers, 0 for zero, and +1 for positive.
bi1 = bi2.subtract(bi3);Returns bi2 - bi3.
Conversion to other values
d = bi.doubleValue();Returns double value equivalent of bi.
f = bi.floatValue();Returns float value equivalent of bi.
i = bi.intValue();Returns int value equivalent of bi.
lng = bi.longValue();Returns long value equivalent of bi.
s = bi.toString();Returns decimal string representation of bi.
s = bi.toString(i);Returns string representation of bi in radix i.
Other
b = bi1.compareTo(bi2);Returns negative number if bi1<bi2, 0 if bi1==bi2, or positive number if bi1>bi2.

 

Random number in java : Shuffling

Monday, 20 September 2010

Hashmap in java

public class HashMapExample{
public static void main(String args[]){
// constructs a new empty HashMap with default initial capacity
HashMap hashMap = new HashMap();
/*
To specify initial capacity, use following constructor.
HashMap HashMap = new HashMap(100);
To create HashMap from map use following constructor
HashMap HashMap = new HashMap(Map myMap);
*/
hashMap.put( "One", new Integer(1) ); // adding value into HashMap
hashMap.put( "Two", new Integer(2) );
hashMap.put( "Three", new Integer(3) );
/*
IMPORTANT : We CAN NOT add primitives to the HashMap. We have to wrap it into one of the wrapper before adding.
*/
/*
To copy all key - value pairs from any Map to HashMap use putAll method.
Signature of putAll method is,
void putAll(Map m)
*/
//get number of keys present in the HashMap
System.out.println("HashMap contains " + hashMap.size() + " key value pair.");
/*
To check whether HashMap is empty or not, use isEmpty() method.
isEmpty() returns true is HashMap is empty, otherwise false.
/*
Finding particular value from the HashMap :
HashMap's containsValue method returns boolean depending upon the presense of the value in given HashMap
Signature of the containsValue method is,
boolean containsValue(Object value)
*/
if( hashMap.containsValue( new Integer(1) ) ){
System.out.println("HashMap contains 1 as value");
}else{
System.out.println("HashMap does not contain 1 as value");
}
/*
Finding particular Key from the HashMap :
HashMap's containsKey method returns boolean depending upon the presense of the key in given HashMap
Signature of the method is,
boolean containsKey(Object key)
*/
if( hashMap.containsKey("One") ){
System.out.println("HashMap contains One as key");
}else{
System.out.println("HashMap does not contain One as value");
}
/*
Use get method of HashMap to get value mapped to particular key.
Signature of the get method is,
Object get(Object key)
*/
Integer one = (Integer) hashMap.get("One");
System.out.println("Value mapped with key \"One\" is " + one);
/*
IMPORTANT:  get method returns Object, so we need to downcast it.
*/
/*
To get all keys stored in HashMap use keySet method.
Signature of the keysSet method is,
Set keySet()
*/
System.out.println("Retriving all keys from the HashMap");
Iterator iterator = hashMap.keySet().iterator();
while( iterator. hasNext() ){
System.out.println( iterator.next() );
}
/*
To get all values stored in HashMap use entrySet() method.
Signature of the entrySet() method is,
Set entrySet()
*/
System.out.println("Retriving all values from the HashMap");
iterator = hashMap.entrySet().iterator();
while( iterator. hasNext() ){
System.out.println( iterator.next() );
}
/*
To remove particular key - value pair from the HashMap use remove method.
Signature of remove methid is,
Object remove(Object key)
This method returns value that had mapped to the given key, otherwise null if mapping not found.
*/
System.out.println( hashMap.remove("One") + " is removed from the HashMap.");
}
}

Output Hashmap in java

/*
OUTPUT of the above given Java HashMap Example would be :
HashMap contains 3 key value pair.
HashMap contains 1 as value
HashMap contains One as key
Value mapped with key "One" is 1
Retriving all keys from the HashMap
Three
Two
One
Retriving all values from the HashMap
Three=3
Two=2
One=1
1 is removed from the HashMap.
*/