Sunday, December 4, 2016

Internal working of HashSet

Set is a collection that contains no duplicate elements. So, it can contain at most one null.
HashSet implements Set interface in java. It is not synchronized and is not thread safe.

Example: Showing HashSet does not allow duplicate elements.

public class Test {
   public static void main(String[] args) throws IOException {
        HashSet hashSet = new HashSet();
        hashSet.add(20);
        hashSet.add("Test");
        hashSet.add("XYZ");
        hashSet.add(20);
        hashSet.add("Test");
        System.out.println("Set = "+hashSet);
   }
}


Output:
Set = [20, Test, XYZ]


Internal Working:
Internally when the duplicate elements are passed to the HashSet, the add(e) method in HashSet returns false when the element exists, else it returns true.

When we have a look at the HashSet.java in java API, we can see the following code:

public class HashSet extends AbstractSet implements Set, Cloneable, java.io.Serializable
{
    private transient HashMap<E,Object> map; 

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

    public HashSet() {
        map = new HashMap<>();
    }

    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

    /**
    * Some code
    */
}

Set achieves the uniqueness in its elements through HashMap. In HashMap, each key is unique. So, when an object of HashSet is created, it will create an object of HashMap.

When an element is passed to Set, it is added as a key in the HashMap in the add(Element e) method. Now, a value needs to be associated to the key. Java uses a Dummy value (new Object) which is called PRESENT in HashSet.

In HashMap, the put(Key k,Value V) method returns null, if the key is unique and the key gets added to the map. It returns old value of the key, if the key is duplicated.

public V put(K key, V value) {
/* Some code */
}

In add(e) method, the return value of map.put(key,value) method is checked with null value.

public boolean add(E e) {
return map.put(e, PRESENT)==null;
}

If map.put(key,value) returns null, then map.put(e, PRESENT)==null will return true and element gets added to the HashSet.

If map.put(key,value) returns the old value of the key, then map.put(e, PRESENT)==null will return false and element wont be added to the HashSet.

remove() method also works in the same way.

public boolean remove(Object o) {
    return map.remove(o)==PRESENT;
}

As you know HashSet uses same values for all keys, it is really important to override equals() and hashCode() for any object you are going to store in HashSet thus making the object Immutable.

Thursday, November 17, 2016

Volatile in JAVA

Volatile keyword can be applied only to variables. It cannot be applied to class or method.

Volatile is used to indicate that a variable's value will be modified by different threads.

The value of volatile variable never get cached thread-locally; all reads and writes go straight to main memory.

A volatile variable can be used as an alternative way of to achieve synchronization in Java in some cases, like visibility. 

With volatile variable, it's guaranteed that all reader threads will see updated value of the volatile variable once write operation is completed, without volatile keyword different reader threads may see different values.

Example:
Imagine a situation in which two or more threads have access to a shared object which contains a counter variable declared like this:

public class SharedVariable {
    public int counter = 0;
}

Imagine too, that only Thread 1 increments the counter variable, but both Thread 1 and Thread 2 may read the counter variable from time to time.

If the counter variable is not declared volatile there is no guarantee about when the value of the counter variable is written from the CPU cache back to main memory. This means, that the counter variable value in the CPU cache may not be the same as in main memory.

The problem with threads not seeing the latest value of a variable because it has not yet been written back to main memory by another thread, is called visibility problem (updates of one thread are not visible to other threads).

By declaring the counter variable volatile all writes to the counter variable will be written back to main memory immediately. Also, all reads of the counter variable will be read directly from main memory. Here is how the volatile declaration of the counter variable looks:

public class SharedVariable {
    public volatile int counter = 0;
}

Declaring a variable volatile thus guarantees the visibility for other threads of writes to that variable.

Sunday, November 13, 2016

Difference between Sleep and Wait

sleep() is a method which is used to hold the process for some time but wait() method causes the thread to go in waiting state and it won’t come back automatically until notify() or notifyAll() is called.

The major difference is that wait() releases the lock while sleep() does not release any lock.

Wait is used for inter-thread communication while sleep is used to introduce pause on execution.

Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread.
Even if we call t.sleep() where t is a different thread; even then, the current thread will sleep, not the t thread.

object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait is called on an object, not a thread; we call this object the lock object. Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread.

Friday, November 11, 2016

Internal working of ArrayList

ArrayList is the most commonly used DataStructure in JAVA.

Internally it conatins an Array of Objects as follows ->
private transient Object[]elementData;

When we actually create an arrayList following piece of code is executed ->
this.elementData=new Object[initial capacity];



ArrayList can be created in two ways ->

1. List<String> myList=new ArrayList<String>(); 
(default constructor is invoked and internally creates an array of Object with default size 10)

2. List<String> myList=new ArrayList<String>(5);
(constructor with an integer argument is invoked and internally creates an array of Object with the size, specified in the constructor argument, which happens to be 5 in this case)



Unlike normal arrays, the size of the ArrayList grows dynamically.

Before adding element into the array it checks the current size of filled elements and the maximum size of the array. If the size of filled elements is greater than maximum size of the array then size of the array increases.

But since size of the array cannot be increased dynamically, internally a new Array is created with size 1.5 * currentSize and data from the old Array is copied into this new Array.

Wednesday, October 26, 2016

Why DDL is faster than DML?

DDL is always and always faster than DML.

After firing DDL statement we cannot fire rollback command, but in DML we can.

The reason being for DML; Oracle stores records in Redo Log Files; and copies them back during rollback.

For DDL statements; Log Files are not maintained.



One common question always asked is this -> What is the difference between Delete and Truncate?

Difference 1: Truncate (DDL) is faster than Delete (DML)

Difference 2: Delete can be rollbacked whereas Truncate can't.

Reason being Redo Log Files not maintained for Truncate.
Home