Tuesday, March 15, 2016

Scala Class and Companion Objects

In Scala you define a class like
   
     class Test(val x: Int) // with one instance variable x

You can instantiate it like
      
        new Test(1)

You can also instantiate it without new (if you think it is too much typing) by defining “companion” object of class
  
    class Test(val x: Int)

    object Test {
        def apply(x: Int) = new X(x)
    }

The object is a “companion” object of class X.  It’s contents is like “static” qualifier in Java.  Moreover, function “apply” is a special name.  You don’t need to write the name of a function if the name is “apply”.  So, you can create an instance of X now with:

    Test.apply(1)
Or
    Test(1)

Tuesday, October 22, 2013

Converting between Collections and Arrays

Collections framework was created long after the large portion of Java Platform API was designed. As a result, we occasionally need to convert between traditional arrays and more modern Collections.

Below are two methods which acts as bridge between array-based and collection-based APIs.
Array to Collections

Arrays.asList(..) is used for this

String[] arrayValues =  ...;

HashSet values = new HashSet<>(Arrays.asList(arrayValues));


Collections to Array

toArray() method - variant 1
result is an array of Objects. You cannot change its type even if we know the type of the objects in collections. This will allocate a new array even if the collection is backed by array so it will be "safe" in that no references to it are maintained by this collection.


Object[] arrayValues = values.toArray(); 

String[] arrayValues = (String[]) values.toArray(); // Error  

toArray(...) method - variant 2
result is an array containing all the elements in collection. The type of the returned array is that of the specified array. If the collection elements fits in the specified array size, it is returned. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection. 
If this collection fits in the specified array with room to spare (i.e., the array has more elements than this collection), the element in the array immediately following the end of the collection is set to null. (This is useful in determining the length of this collection only if the caller knows that this collection does not contain any null elements.) 


String[] arrayValues =  value.toArray(new String[0]); // creates new array

String[] arrayValues =  value.toArray(value.size()); // no new array is created

Wednesday, October 9, 2013

PriorityQueue with Example

PriorityQueue is added in Collections family as part of Jav1.5. It retrieves element in sorted order irrespective of their insertion order. Sorting will be done either based on the natural order of the element or the custom order defined by the Comparable interface or the Comparator object supplied in the constructor.

Head of the PriorityQueue always contain least element with respect to specific ordering. Queue retrieval methods like remove(), poll(), peek() and element() access head of Queue, which keeps least element according to specified ordering in the queue. 

PriorityQueue does not sort out all the elements and if you iterate over the elements the retrieval order will be different. This is infact the  main difference between TreeSet and PriorityQueue in Java, Treeset keeps all elements in a particular sorted order, while PriorityQueue only keeps head in sorted order.

PriorityQueue doesn't permit null elements and trying to add null elements will result in NullPointerException.

PriorityQueue is not synchronized, use BlockingPriorityQueue for thread safety.

PriorityQueue make use of data structure called 'HEAP' - a self organizing binary tree in which add() and remove() methods cause the smallest element to save to the root, without wasting time on sorting all the elements. 
 
Complexity:
PiorityQueue provides O(log(n)) time performance for common enqueing and dequeing methods e.g. offer(), poll() and add(), but constant time for retrieval methods e.g. peek() and element().
 
Typical Use:
Job Scheduling.
Useful in implementation of Dijkstra algorithm in Java. 


Job Scheduling Example:
Each job has a priority. Jobs are added in random order. A highest priority job is removed from the queue.
package collections;

import java.util.PriorityQueue;

public class PriorityQueueTest {

    public static void main(String[] args){
        PriorityQueue<Job> prQueue = new PriorityQueue<Job>();
        prQueue.add(new Job("Job 5", 5));
        prQueue.add(new Job("Job 4", 4));
        prQueue.add(new Job("Job 3", 3));
        prQueue.add(new Job("Job 1", 1));
        prQueue.add(new Job("Job 2", 2));
  //prQueue.add(null); // null elements not allowed in PriorityQueue - 
// NullPointerException
        
        System.out.println("Iterating Over the Elements - No Specific Oder or Sorting");
        for(Job job: prQueue){
            System.out.println(job.getJobName());
        }
        
        System.out.println("Removing the Elements - Sorted based on the job priority - CompareTo method");
        while(!prQueue.isEmpty()){
            System.out.println(prQueue.remove().getJobName());
        }
    }
    
    private static class Job implements Comparable <Job>{

        private String jobName;
        private int jobPriority;
        
        public Job(String jobName, int priority){
            this.jobName = jobName;
            this.jobPriority = priority;
        }

        public String getJobName() {
            return jobName;
        }
        public void setJobName(String jobName) {
            this.jobName = jobName;
        }
        public int getJobPriority() {
            return jobPriority;
        }
        public void setJobPriority(int jobPriority) {
            this.jobPriority = jobPriority;
        }
        
        @Override
        public int compareTo(Job job) {
            if(this.jobPriority == job.jobPriority){
                return this.jobName.compareTo(job.jobName);
            }
            return this.jobPriority - job.jobPriority;
        }
    }
}

 

Friday, June 28, 2013

java.util.Timer - Example

Timer class in java gives capability to schedule tasks for future execution in a background thread.
Task can be schedule for one time execution or for multiple times after specified regular intervals.

Example
 We will use Timer class to maintain a count of tasks processed in last one minute, five minute and ten minutes. We will also use AtomicInteger

 

 import java.util.Timer;

import java.util.TimerTask;

import java.util.concurrent.atomic.AtomicInteger;

public class TimerTest extends Timer

{

    private final AtomicInteger oneMinuteCounter;

    private final AtomicInteger fiveMinuteCounter;

    private final AtomicInteger tenMinuteCounter;

    public static final long MILLIS_IN_MINUTE = 60000;

    private Timer taskManager = new Timer("taskManager");

    public TimerTest()

    {

        oneMinuteCounter = new AtomicInteger(0);

        fiveMinuteCounter = new AtomicInteger(0);

        tenMinuteCounter = new AtomicInteger(0);

    }

    protected static class Decrement extends TimerTask

    {

        private final AtomicInteger atomicInteger;

        public Decrement(AtomicInteger integer)

        {

            atomicInteger = integer;

        }

        @Override

        public void run()

        {

            atomicInteger.decrementAndGet();

        }

    }

    public void executeTask()

    {

        oneMinuteCounter.incrementAndGet();

        taskManager.schedule(new Decrement(oneMinuteCounter), MILLIS_IN_MINUTE);

        fiveMinuteCounter.incrementAndGet();

        taskManager.schedule(new Decrement(fiveMinuteCounter), 5 * MILLIS_IN_MINUTE);

        tenMinuteCounter.incrementAndGet();

        taskManager.schedule(new Decrement(tenMinuteCounter), 5 * MILLIS_IN_MINUTE);

    }

 

    public void printTaskExecution()

    {

        System.out.println(oneMinuteCounter.get());

        System.out.println(fiveMinuteCounter.get());

        System.out.println(oneMinuteCounter.get());

    }

    public static void main(String... args)

    {

        TimerTest timer = new TimerTest();

       for(int i=0; i &amp;lt;1000 ; i++)

           try
            {
                timer.executeTask();
                Thread.sleep(10000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}




Friday, June 14, 2013

Ruannable vs Callable<T>


"The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception."

Runnable Callable<T>
Introduced in Java 1.0 Introduced in Java 1.5 as part of java.util.concurrent library
Runnable cannot be parametrized  Callable is a parametrized type whose type parameter indicates the return type of its run method
Classes implementing Runnable needs to implement run() method Classes implementing Callable needs to implement call() method
Runnable.run() returns no Value Callable.call() returns a value of Type T
Can not throw Checked Exceptions Can throw Checked Exceptions
public class RunnableTest implements Runnable {
              @Override
              public void run() {
                         //any processing
              }
}
import java.util.concurrent.Callable;


public class CallableTest implements Callable
          @Override 
           public String call() throws Exception { 
                      // any processing
                    return new String("I am Callable and can return value and throw checked exception"); 
              } 
}

Monday, June 3, 2013

Code Coverage - Eclipse Plugin

Sunday, June 2, 2013

String Literal Pool or String Constant Pool or String Pool.

Recently one of the colleague asked me - What is String Pool?
I was surprised that this being one of the important concept in java lot of people are not aware of this. So I thought of just jotting down couple of points to explain it.
Hope it helps someone.

To Understand the concept of String Pool - the first thing you need to know - What are String 'Literals?
Literal in general means any number, text or information which represent a value. To make things simple, we can say - A String literal is a sequence of characters in a single line and has to be in double-quotes ("") e.g. "literal".

Now coming back to the concept of String Pool - most of the times we create String in java in either of two ways

String object = new String("object");
String literal = "literal" - String Literal

Whenever you are using a new Operator you are telling the java compiler to create a new Object on the HEAP. Consider a scenario where you have to  use the same String 'object' at multiple places in your program and you use the new operator every time to create it. This will basically create multiple instances of same String on Heap. Calling new String("object") never makes sense in Java and is unnecessarily inefficient and puts additional burden on memory.

Now java designers came out with a solution for this problem. They created a separate cache and called it String Constant Pool or String Literal Pool or String Pool - which maintains a reference of all the String literals created in the program. To put it in simple words, 'string pool' comes from the idea that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined.

So how this works?

When a .java file is compiled into a .class file, any String literals are noted in a special way, just as all constants are. When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for String literals.

JVM encounters statement like String s1 = "literal";.
JVM checks the String pool to see if an equivalent String is already referenced from the heap.
If the String does not exist, it creates a new String object "literal" on the heap and its reference is maintained in the pool (constant table).
This statement creates one String object "literal" on heap.
Variable ‘s1′ refers to the same object.

JVM encounters another statement like String s2 = "literal";
JVM checks the String pool again.
Since the String with same value already exists in heap, a reference to the pooled instance is returned to s2.
This statement does not create any String object in the memory
Variable ‘s2′ refers the same object as ‘s1′.

You can check the above by comparing == operator on s1 and s2. It will always return true.

Some Facts about String Pool :-
  • String pooling is possible only because Strings in java are 'Immutable'.
  • All the string literals are created and their references are placed in the pool while JVM loads the class.
  • Designed on Fly Weight Design Pattern.
  • In early JVM's String literals in the String Pool never got GC'ed. In the newer JVM's, WeakReferences are used to reference the Strings in the pool, so interned Strings can actually get GC'ed, but only during Full Garbage collections.
  • Java automatically interns String literals.
  • You can use .intern() method of new String() not to create a new object on heap instead get the reference from String pool if already present and if not present then it will create a new object on the heap and add the reference to the string pool.

Wednesday, April 24, 2013

Kill a Proccess Running on Winodws Port - Localhost

I was struggling for couple of hours while running a Junit.
To execute it I need to run a hazelcast instance on localhost first but somehow the Hazelcast was running at those port becasue of which my junit keep hanging and waiting for the port to be release.

Just find out a way to figure out to manually kill the port

  • List the processes running on ports
        netstat -a -o -n
  • Look for the process you need get the PID.
        taskkill /F /PID XXX

Sunday, December 2, 2012

Comparator and Comparable in Java

Sorting in Java is easy if you are clear with its fundamentals. Two basic building blocks which java provides for sorting are Comparator and Comparable interfaces. Java designers have implemented these two interfaces in most of the API classes like String, Integer, BigDecimal, Date etc to provide default or in other words natural ordering of objects.

Collection classes also rely on the implementation of these interfaces to sort the collections of objects they are holding. Sorted collections classes like TreeMap or TreeSet can only contain collection of object which implement comparable or other wise we need to explicitly provide a comparator. If you try to save the collection of objects and don't provide a Comparator then TreeSet / TreeMap assumes that the elements implement Comparable. In case it is not - you will get a classCastException.
To do sorting on objects in non sorted collection classes like HashMap, Arraylist etc we need to use sot method of Collections utility class and provide a comparator to it as well. 

Following are some of the theoretical and logical differences in these two interfaces

Comparator Comparable
Is in java.util package which implicitly says that this is a utility to sort java objects. Is in java.lang package.
Used to implement customized ordering of objects.  Used to implement natural ordering of objects. It make the implementing class comparable (by default).
Has public int compare (Object o1, Object o2) method. Returns -ve, 0 or +ve integer based on whether first argument is <, = or > the second argument. Has public int compareTo(Object o1)
method. Returns -ve, 0 or +ve integer based on whether this object is <, = or > the specified object.
Used to compare two objects provided to it. Used to compare the 'this' reference of object with other specified object.
Objects which don't implement comparable can be used as keys in sorted collections structures like SortedMap (TreeMap) or SortedSet (TreeSet) only by specifying a comparator. Objects implementing comparable can be used as keys in sorted collections structures like SortedMap (TreeMap) or SortedSet (TreeSet).


In Summary if there is a natural or default way of sorting Object already exist during
development of Class than use Comparable like Employee can be sorted by there Id etc.
On the other hand if an Object can be sorted on multiple ways and client is specifying
on which parameter sorting should take place than use Comparator for example
Employee can again be sorted on name or department etc. Comparator implementation
can sort out this problem.


// Employee Class : default sorting is based employeeId.

public class Employee implements Comparable{

    private String employeeId;
    private String employeeFirstName;
    private String department;
    private String employeeLastName;
    
    public Employee(String empId, String firstName, String lastName, String dept) {
        this.employeeId = empId;
        this.employeeFirstName = firstName;
        this.employeeLastName = lastName;
        this.department = dept;
    }
    public String getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }
    public String getEmployeeFirstName() {
        return employeeFirstName;
    }
    public void setEmployeeFirstName(String employeeFirstName) {
        this.employeeFirstName = employeeFirstName;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String dept) {
        this.department = dept;
    }
    public String getEmployeeLastName() {
        return employeeLastName;
    }
    public void setEmployeeLastName(String employeeLastName) {
        this.employeeLastName = employeeLastName;
    } 
    public String toString() {
        return this.employeeId + " : " + this.employeeFirstName + " "
                + this.employeeLastName + " : " + this.department;
    }
        //overrided method to do the default sorting based on employeeId

        public int compareTo(Employee emp) {
        int thisEmployeeId = Integer.valueOf(this.employeeId).intValue();
        int anotherEmployeeId = Integer.valueOf(emp.employeeId).intValue();
        if (thisEmployeeId &gt; anotherEmployeeId) {
            return 1;
        } else if (thisEmployeeId &lt; anotherEmployeeId) {
            return -1;
        }
        return 0;
               // Dont use difference of integers to decide output of compareTo method
               // as result of integer subtraction can overflow but if you are sure that both
               // operands are positive then its one of the quickest way to compare two objects.
               // return thisEmployeeId - anotherEmployeeId;
        }
}

//Comparator which does the sorting on Employee first name
public class EmployeeNameComparator implements Comparator {
    public int compare(Employee emp1, Employee emp2) {
        return emp1.getEmployeeFirstName().compareTo(emp2.getEmployeeFirstName());
    }
}

public class ComparatorbleTest {
    
    public static void main(String... args){
        Employee emp = new Employee("67899", "Richard", "Bar", "Artist");
        Employee emp1 = new Employee("12345", "Michelle", "Steven", "Acting");
        Employee emp2 = new Employee("78900", "Alex", "Fox", "Hollywood");
        Employee emp3 = new Employee("69875", "Salman", "Khan", "Bollywood");
        Employee emp4 = new Employee("09455", "Gangnam", "Style", "Singing");
        List empList = new ArrayList();
        empList.add(emp);
        empList.add(emp1);
        empList.add(emp2);
        empList.add(emp3);
        empList.add(emp4);
                //since the object implements comparable it will by default sort
                // objects in the list by employee id.
        Collections.sort(empList);
        for(Employee employee : empList){
            System.out.println(employee.toString());
        }
        System.out.println("");
                // to do a customized sort (first name) on employee list we 
                // need to provide a corresponding customized comparator. 
        Collections.sort(empList, new EmployeeNameComparator());
        for(Employee employee : empList){
            System.out.println(employee.toString());
        }
    }
}