Monday, October 18, 2010

Collections- Sets

 Collection framework source:
The three types of collections extending Collections interface are
  • List - anything, in the order of addition
  • Set- no duplicates
  • Queue- peep and pop operations
Map is another type of collection where key, value pair is handled.

Set
This collection does not accept duplicate objects.



HashSet
HashSet is backed by HashMap, which implies that there is no preservation of insertion order. Also since the inserted elements are not sorted, just remember that this could allow null element as well.

TreeSet
Inserted elements are sorted based on the supplied Comparator or natural ordering. This is backed by TreeMap which cannot take null as key.

Thursday, October 14, 2010

Callable and ExecutorService

Callable objects is like a Runnable but the Callable object returns ability to monitor, cancel and obtain a result.

Future: A Future represents the result of an asynchronous computation. Its get() waits for the submitted task to complete and returns the result.

ExecutorService: submit method en-queues the submitted Callable and returns a Future to track its completion and obtain the result.

public class CallableDemo {
        public static void main(String...strings ){
            try {
                System.out.println(Thread.currentThread().getName());
                ExecutorService executor=new ScheduledThreadPoolExecutor(5);
                Callable<Date> callable=new Callable<Date>(){
                    @Override
                    public Date call() throws Exception {
                        System.out.println(Thread.currentThread().getName());
                        return new Date();                        
                    }
                };
                Future<Date> fDate=executor.submit(callable);
                System.out.println(fDate.get());
            } catch (Exception e) {}
        }
}




FutureTask- Lets you run a Callable impl to directly run on a thread, instead of submitting to a ExecutorService.
FutureTask task=new FutureTask(new CallableImpl());
Thread t1=new Thread(task);
t1.start();
while(!task.isDone());
task.get();  //get the result

Wednesday, October 13, 2010

Immutable Objects

This study is part of work on Concurrency Programming in Java.

Immutable Object- state cant be altered.

The wrapper classes, Byte, Character, Short, Integer, Long, Float and Double are all immutable. Strings are immutable.

How to construct an immutable object?
  • Simplest way would be to mark all the fields as final.
  • Declare the member fields as private and not to provide any setter methods, and letting it all to be initialized through constructor only.
In case the object gets a reference to other object, get the reference to a copy(clone) of that object. This way the referenced object is hidden from the user, thus the object is immutable as whole.
public class Order {
    private String orderId;
    private int quantity;
    private BookProperties bookProperties;
    public Order(String orderId,int quantity,BookProperties props){
        this.orderId=orderId;
        this.quantity=quantity;
        this.bookProperties=(BookProperties)props.clone();        
    }
    public String getOrderId(){
        return orderId;
    }
    public int getQuantity(){
        return quantity;
    }
    public BookProperties getBookProperties(){
        return bookProperties.clone();
    }
}
Note: Do not let the object to be reference before the object is completely constructed, this could be difficult in concurrent environment.

Advantages of Immutable objects
Immutable objects are state consistent value containers, thus
  • Immutable object can never encounter conflicts or inconsistencies when multiple threads accesses it.
  • Immutable objects are more suitable for HashTable keys. If the 'key' object state could be altered then we may lose the mapping.
Immutable objects allow shared references, thus
  • Duplicate objects can be avoided improving space efficiency. (eg)String
Why is String Immutable?
String is a value object like primitive variables whose value should never be changed. Making String an immutable object is linked to Security and space concern, may be it
  • in javac which is written on java and it uses lots of String objects containing parsed name that are not to be altered. The reason was felt so strong that String was made immutable in JLS.
  • in JVM's SecurityManager allowing the code to access resources. Consider a situation where we have to validate a legitimate site and then let him/her connect to it. If the String mutable, immediately after verification the host name could be altered and connection would be made to a different server.
  • An important feature of immutability is, the object reference can be shared for space efficiency and yet have no access restrictions or syncronization concern. A same string object can be referenced from many other objects.
How do I make my method return an immutable reference?
  • Wrap the reference in an immutable wrapper class and return that.
  • Return an immutable interface to the original data.
  • You can return an Iterator with a dummy remove method.
  • In case of Collections, use the available Collection.unmodifiableCollection methods.

code block test

Used SyntaxHighlighter theme and js to support code listing in blogs.
Add following styles and js libraries to the html layout:
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/> 
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeEclipse.css' rel='stylesheet' type='text/css'/> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'/>
The above includes theme(I use Eclipse theme and js & java brush, i.e. the syntax highlighter)
If the sample code has any xml markup, it needs to be escaped, use this tool.
sample as below:
class AppAProperties{
    int a;
    private String b;
    private UserCredential user;
    public AppProperties(int a, String b, UserCredential user){
        this.a=a;
        this.b=b;
        this.user=(UserCredential )user.clone();
    }
    // no setter methods . .
}