Steps to setup DB2 Data Studio Client for Visual Explain of queries.

As a beginner, It was hard for me to figure out how to prepare visual execution plan in DB2 Data Studio Client. I was ending up with the following error.
com.ibm.datatools.dsoe.common.da.exception.OSCSQLException: com.ibm.db2.jcc.am.SqlSyntaxErrorException: The required Explain table "VICKY.EXPLAIN_INSTANCE" does not exist.. SQLCODE=-219, SQLSTATE=42704, DRIVER=3.68.61
     at com.ibm.datatools.dsoe.explain.luw.impl.ExplainThread.explain(Unknown Source)
     at com.ibm.datatools.dsoe.explain.luw.impl.ExplainThread.buildLUWExplainModelNeedSync(Unknown Source)
     at com.ibm.datatools.dsoe.explain.luw.impl.ExplainThread.commonProcess(Unknown Source)
     at com.ibm.datatools.dsoe.explain.luw.impl.ExplainThread.process(Unknown Source)
     at com.ibm.datatools.dsoe.explain.luw.Explainer.process(Unknown Source)
     at com.ibm.datatools.dsoe.ape.core.LUWAPEModelGenerator.generate(Unknown Source)
     at com.ibm.datatools.dsoe.ape.core.APEModelGenerator.generate(Unknown Source)
     at com.ibm.datatools.visualexplain.common.viewer.popup.LaunchVisualExplainFromEditorAction$1.run(Unknown Source)
     at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(Unknown Source)
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: The required Explain table "VICKY.EXPLAIN_INSTANCE" does not exist.. SQLCODE=-219, SQLSTATE=42704, DRIVER=3.68.61
     at com.ibm.db2.jcc.am.gd.a(Unknown Source)
     at com.ibm.db2.jcc.am.gd.a(Unknown Source)
     at com.ibm.db2.jcc.am.gd.a(Unknown Source)
     at com.ibm.db2.jcc.am.uo.c(Unknown Source)
     at com.ibm.db2.jcc.am.uo.d(Unknown Source)
     at com.ibm.db2.jcc.am.uo.a(Unknown Source)
     at com.ibm.db2.jcc.t4.bb.h(Unknown Source)
     at com.ibm.db2.jcc.t4.bb.b(Unknown Source)
     at com.ibm.db2.jcc.t4.p.a(Unknown Source)
     at com.ibm.db2.jcc.t4.vb.i(Unknown Source)
     at com.ibm.db2.jcc.am.uo.ib(Unknown Source)
     at com.ibm.db2.jcc.am.uo.a(Unknown Source)
     at com.ibm.db2.jcc.am.uo.e(Unknown Source)
     at com.ibm.db2.jcc.am.uo.execute(Unknown Source)
     ... 9 more


Steps to setup Visual Explain

Step 1: Switch Data Studio Activity. Administer Databases to Tune Queries (As shown in Image)

Administer Databases to Tune Queries+ DB2 Data Studio Client

Step 2: Right click Data Source. Analyze and Tune > Configure and Tuning > Guided Configuration (As shown in Image)


Now you can generate visual explain on your queries.

Example of Comparable in Java


Comparable<T>
This 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.

Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

You can use Comparator when you want different sorting option as per requirement. And you would also like to read How to sort List of Bean in Java? using Comparator and Comparable and How to sort Array in Ascending, Descending and Mixed mode in Java?

Source code (ComparableItem.java)
/**
 * Comparable item.
 * @author javaQuery
 * @date 11th August, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ComparableItem implements Comparable<ComparableItem>{

    private String name;
    private Double price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
    
    @Override
    public int compareTo(ComparableItem item) {
        if(item != null && item.getName() != null){
            return this.getName().compareTo(item.getName());
        }
        return -1;
    }

    @Override
    public String toString() {
        return "ComparableItem{" + "name=" + name + ", price=" + price + '}';
    }
}

Source code (ComparableExample.java)
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Example of Comparable.
 * @author javaQuery
 * @date 11th August, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ComparableExample {

    public static void main(String[] args) {
        ComparableItem samsung = new ComparableItem();
        samsung.setName("samsung");

        ComparableItem iphone = new ComparableItem();
        iphone.setName("iphone");

        List<ComparableItem> comparableItems = new ArrayList<ComparableItem>(2);
        comparableItems.add(samsung);
        comparableItems.add(iphone);
        
        new ComparableExample().performSort(comparableItems);
    }

    /**
     * Print list to console
     *
     * @param items
     */
    private void printListData(List<ComparableItem> items) {
        for (ComparableItem item : items) {
            System.out.println(item);
        }
    }
    
    /**
     * Perform sort on give List
     * @param comparableItems 
     */
    private void performSort(List<ComparableItem> comparableItems){
        System.out.println("Before sort:");
        printListData(comparableItems);
        System.out.println("===============================================");
        Collections.sort(comparableItems);
        System.out.println("After sort(orderByNameASC):");
        printListData(comparableItems);
    }
}

Output
Before sort:
ComparableItem{name=samsung, price=null}
ComparableItem{name=iphone, price=null}
===============================================
After sort(orderByNameASC):
ComparableItem{name=iphone, price=null}
ComparableItem{name=samsung, price=null}

Example of Comparator in Java

Comparator<T>
A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.

You can use Comparable when you want natural ordering on class. And you would also like to read How to sort List of Bean in Java? using Comparator and Comparable and How to sort Array in Ascending, Descending and Mixed mode in Java?

Source code (Item.java)
import java.util.Comparator;

public class Item {

    private String name;
    private Double price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
    
    /**
     * Comparator to sort {@link Item} in ascending order by name.
     */
    public Comparator<Item> orderByNameASC(){
        return new Comparator<Item>() {
            @Override
            public int compare(Item o1, Item o2) {
                if(o1 != null && o1.getName() != null
                        && o2 != null && o2.getName() != null){
                    return o1.getName().compareTo(o2.getName());
                }
                return -1;
            }
        };
    }
    
    /**
     * Comparator to sort {@link Item} in descending order by name.
     */
    public Comparator<Item> orderByNameDESC(){
        return new Comparator<Item>() {
            @Override
            public int compare(Item o1, Item o2) {
                if(o1 != null && o1.getName() != null
                        && o2 != null && o2.getName() != null){
                    return o2.getName().compareTo(o1.getName());
                }
                return -1;
            }
        };
    }

    @Override
    public String toString() {
        return "Item{" + "name=" + name + ", price=" + price + '}';
    }
}

Source code (ComparatorExample.java)
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Example of Comparator.
 * @author javaQuery
 * @date 9th August, 2016
 * @Github: https://github.com/javaquery/Examples 
 */
public class ComparatorExample {

    public static void main(String[] args) {
        Item samsung = new Item();
        samsung.setName("samsung");

        Item iPhone = new Item();
        iPhone.setName("iphone");

        List<Item> items = new ArrayList<Item>(2);
        items.add(samsung);
        items.add(iPhone);

        List<Item> clonedItems = new ArrayList<Item>(items);
        new ComparatorExample().usingPredefinedComparator(clonedItems);
        new ComparatorExample().usingInLineExpression(clonedItems);
        new ComparatorExample().usingLambdaExpression(new ArrayList<Item>(items));
    }

    /**
     * Print list to console
     *
     * @param items
     */
    private void printListData(List<Item> items) {
        for (Item item : items) {
            System.out.println(item);
        }
    }

    /**
     * Considering you've already created Comparators in your model.
     *
     * @param items
     */
    private void usingPredefinedComparator(List<Item> items) {
        System.out.println("Using Predefined Comparator (NAME#ASC)");
        System.out.println("===============================================");
        System.out.println("Before sort:");
        printListData(items);
        System.out.println("After sort(orderByNameASC):");
        Collections.sort(items, new Item().orderByNameASC());
        printListData(items);
    }
    
    /**
     * This is same as PredefinedComparator. 
     * Its only to show you how to use {@link Comparator} in-line.
     * @param items 
     */
    private void usingInLineExpression(List<Item> items){
        System.out.println("===============================================");
        System.out.println("Using Inline Expression (NAME#DESC)");
        System.out.println("===============================================");
        System.out.println("Before sort:");
        printListData(items);
        System.out.println("After sort(orderByNameDESC):");
        Collections.sort(items, new Comparator<Item>(){

            @Override
            public int compare(Item o1, Item o2) {
                if(o1 != null && o1.getName() != null
                        && o2 != null && o2.getName() != null){
                    return o2.getName().compareTo(o1.getName());
                }
                return -1;
            }
             
        });
        printListData(items);
    }
    
    /**
     * Using Lambda Expression in Java 1.8 or above.
     * @param items 
     */
    private void usingLambdaExpression(List<Item> items){
        System.out.println("===============================================");
        System.out.println("Using Lambda Expression (NAME#DESC)");
        System.out.println("===============================================");
        System.out.println("Before sort:");
        printListData(items);
        System.out.println("After sort(orderByNameASC):");
        Collections.sort(items, (Item o1, Item o2) -> {
            if(o1 != null && o1.getName() != null
                    && o2 != null && o2.getName() != null){
                return o1.getName().compareTo(o2.getName());
            }
            return -1;
        });
        printListData(items);
    }
}

Output
Using Predefined Comparator (NAME#ASC)
===============================================
Before sort:
Item{name=samsung, price=null}
Item{name=iphone, price=null}
After sort(orderByNameASC):
Item{name=iphone, price=null}
Item{name=samsung, price=null}
===============================================
Using Inline Expression (NAME#DESC)
===============================================
Before sort:
Item{name=iphone, price=null}
Item{name=samsung, price=null}
After sort(orderByNameDESC):
Item{name=samsung, price=null}
Item{name=iphone, price=null}
===============================================
Using Lambda Expression (NAME#ASC)
===============================================
Before sort:
Item{name=samsung, price=null}
Item{name=iphone, price=null}
After sort(orderByNameASC):
Item{name=iphone, price=null}
Item{name=samsung, price=null}

How Fail Fast Iterator identifies that the collection is modified?



Image gives you the abstract idea about How iterator identifies the modification on collection. Its one of the interview question asked as sub part of Fail Fast vs Fail Safe Iterator in Java. To understand it better I pulled out the source code of HashMap.

Source code (HashMap.java)
public class HashMap<K, V>...{
    transient int modCount;

    public V put(K key, V value) {
        return this.putVal(hash(key), key, value, false, true);
    }

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        ...
        ++this.modCount;
        ...
    }
 
    public Set<Map.Entry<K,V>> entrySet() {
        // this method internally uses HashIterator
    }

    abstract class HashIterator{
        int expectedModCount;  // for fast-fail
        ...
        HashIterator() {
            expectedModCount = modCount;
            ...
        }
 
        final Node nextNode() {
            ...
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            ...
            ...
        }
    }
}
So when you call method entrySet() of HashMap, It creates the object of inner class HashIterator with current value of modCount and set it in expectedModCount.

Now when nextNode() method is called it compares value of expectedModCount with parent class's (HashMap) modCount and if its not same then it throws ConcurrentModificationException.

Source code (FailFastExample.java)
/**
 * Example of Fail Fast using Map.
 * @author javaQuery
 * @date 4th August, 2016
 * @Github: https://github.com/javaquery/Examples 
 */
public class FailFastExample {
    public static void main(String[] args) {
        Map<String, Double> carPrice = new HashMap<String, Double>();
        carPrice.put("Porsche", 100000D);
        carPrice.put("Ferrari", 200000D);

        /* Iterate over Map */
        for(Map.Entry<String, Double> car : carPrice.entrySet()){
            System.out.println("Car: " + car.getKey());
            System.out.println("Price: " + car.getValue());
            
            /* Will cause java.util.ConcurrentModificationException */
            carPrice.put("Lamborghini", 300000D);
        }
    }
}

Output
Car: Ferrari
Price: 200000.0
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
 at java.util.HashMap$EntryIterator.next(HashMap.java:1463)
 at java.util.HashMap$EntryIterator.next(HashMap.java:1461)
 at com.javaquery.collections.map.FailFastExample.main(FailFastExample.java:23)

Fail Fast vs Fail Safe Iterator in Java

Fail Fast vs Fail Safe


One of the popular interview question asked to java developer. To know how well you understand the iterator.

Fail Fast
When you perform add, update or remove on collection while iterating on it. It throws java.util.ConcurrentModificationException.

Source code (FailFastExample.java)
import java.util.HashMap;
import java.util.Map;

/**
 * Example of Fail Fast using Map.
 * @author javaQuery
 * @date 4th August, 2016
 * @Github: https://github.com/javaquery/Examples 
 */
public class FailFastExample {
    public static void main(String[] args) {
        Map<String, Double> carPrice = new HashMap<String, Double>();
        carPrice.put("Porsche", 100000D);
        carPrice.put("Ferrari", 200000D);

        /* Iterate over Map */
        for(Map.Entry<String, Double> car : carPrice.entrySet()){
            System.out.println("Car: " + car.getKey());
            System.out.println("Price: " + car.getValue());
            
            /* Will cause java.util.ConcurrentModificationException */
            carPrice.put("Lamborghini", 300000D);
        }
    }
}

Output
Car: Ferrari
Price: 200000.0
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
 at java.util.HashMap$EntryIterator.next(HashMap.java:1463)
 at java.util.HashMap$EntryIterator.next(HashMap.java:1461)
 at com.javaquery.collections.map.FailFastExample.main(FailFastExample.java:23)

You can also consider Collection (List, Set, Map) shared between two or more Threads. One is iterating on collection and other tries to add element in it then the thread iterating over it, will throw java.util.ConcurrentModificationException

In interview if you are able to answer this question. They might me interested in checking your knowledge little bit deep. You may face the question How Fail Fast Iterator identifies that the collection is modified?

Fail Safe
It iterate over the clone(copy) of original collection. So It won't throw java.util.ConcurrentModificationException.

Source code (FailSafeExample.java)
/**
 * Example of Fail Safe using ConcurrentHashMap.
 * @author javaQuery
 * @date 4th August, 2016 
 * @Github: https://github.com/javaquery/Examples 
 */
public class FailSafeExample {

    public static void main(String[] args) {
        Map<String, Double> carPrice = new ConcurrentHashMap<String, Double>();
        carPrice.put("Porsche", 100000D);
        carPrice.put("Ferrari", 200000D);

        /* Iterate over Map */
        for (Map.Entry<String, Double> car : carPrice.entrySet()) {
            System.out.println("Car: " + car.getKey());
            System.out.println("Price: " + car.getValue());

            /* Will be added in original copy of Map but won't available in Iterator */
            carPrice.put("Lamborghini", 300000D);
        }
        System.out.println("=== loop finished ===");
        System.out.println("Car: Lamborghini" + ", Price: " + carPrice.get("Lamborghini"));
    }
}

Output
Car: Ferrari
Price: 200000.0
Car: Porsche
Price: 100000.0
=== loop finished ===
Car: Lamborghini, Price: 300000.0

Difference between Thread start() and Runnable run()

Lets first understand run() method of Runnable. Consider following code snippet.

Source code (Car.java)
public class Car implements Runnable{

    @Override
    public void run() {
        System.out.println("Run car...");
    }
}
Source code (Cycle.java)
public class Cycle{

    public void run() {
        System.out.println("Run cycle...");
    }
}
public class Test {
    public static void main(String[] args) {
        /* Calling method of class Cycle */
        new Cycle().run();
        /* Calling method of class Car, doesn't matter class implements Runnable */
        new Car().run();
    }
}
There is no difference between new Cycle().run() and new Car().run() even if Car implements Runnable . You are just calling method of class Car.

Runnable in Thread
public class Test {
    public static void main(String[] args) {
        Thread thread = new Thread(new Car());
        /* It'll start new Thread and call run method of Car() in Thread environment */
        thread.start();
    }
}
run method of Car will be executed in separate Thread environment. thread.start() will start new Thread.

Conclusion
- run method of Runnable will be executed as normal method of class.
- start method of Thread starts the new Thread.

Difference between Thread and Runnable in Java

extends Thread vs implements Runnable

Inheritance
Java supports only single Inheritance means you can't extend more than one class. When you extends Thread you lose the opportunity to extend another class.

Implementing Runnable interface gives you window to extend another class.

Extending class
Extending class means you are changing behavior of super class with your implementation. Since you are not changing the behavior of Thread, implement Runnable.

Runnable as Task
Implementing Runnable represents standalone Task and can be executed by simple Thread or Executors.

Runnable means we can reuse the Task, but you can't restart the Thread once it completes.

Executor Interface
Since you can't restart the Thread once it completes, Java designer decided to accept Runnable class in Executor Interface and it gives more control over your Task compare to Thread.