Exception Handling with Inheritance

Quick Reference :

  • Unchecked exception can be thrown anywhere in parent and child and there is no issues with that
  • Super class has exception in signature then child class can have subclass of that exception or no exception at all and this is fine
  • Subclass cannot but Exception in it

Types of problems:

There are two types of problems associated with it which are as follows:

  1. Problem 1: If The SuperClass doesn’t declare an exception
    1. Case 1: If SuperClass doesn’t declare any exception and subclass declare checked exception : Compile Time Error
    2. Case 2: If SuperClass doesn’t declare any exception and SubClass declare Unchecked exception : Allowed
  2. Problem 2: If The SuperClass declares an exception
    1. Case 1: If SuperClass declares an exception and SubClass declares exceptions other than the child exception of the SuperClass declared Exception. : Compile time error
    2. Case 2: If SuperClass declares an exception and SubClass declares a child exception of the SuperClass declared Exception. : Allowed
    3. Case 3: If SuperClass declares an exception and SubClass declares without exception. : Allowed

Conclusion

  • If SuperClass does not declare an exception, then the SubClass can only declare unchecked exceptions, but not the checked exceptions.
  • If SuperClass declares an exception, then the SubClass can only declare the same or child exceptions of the exception declared by the SuperClass and any new Runtime Exceptions, just not any new checked exceptions at the same level or higher.
  • If SuperClass declares an exception, then the SubClass can declare without exception.

Difference between ? and T i.e Unbounded Wildcard and T

I stumbled upon a function looking like this:

public void function(Class<?> clazz) {...}

What are the pros/cons of changing the method to:

public <T> void function(Class<T> clazz) {...}

Using “?” is the same as “any”, whereas “T” means “a specific type”. So, compare these interfaces:

public interface StrictClass<T> {
 public T doFunction(Class<T> class);
}

public interface EasyClass<T> {
 public > doFunction(Class<?> class);
}

Now, we can create classes:

public class MyStrictClass implements StrictClass<String> {
  public String doFunction(Class<String> stringClass) {
    //do something here that returns String
  }
}

public class MyEasyClass implements EasyClass<String> {
  public String doFunction(Class<?> anyClass) {
    //do something here that returns String
  }
}

todd.run is totally right on, but that’s only half the answer. There are also use cases for choosing <T> over <?> (or vice versa) that apply when you don’t add type parameter to the class that encloses the method. For example, consider the difference between

public <E extends JLabel> boolean add(List<E> j) {
    boolean t = true;
    for (JLabel b : j) {
        if (b instanceof JLabel) {
            t = t &amp;&amp; labels.add(b);
        }
    }
    return t;
}

and

public boolean add(List<? extends JLabel> j) {
    boolean t = true;
    for (JLabel b : j) {
        if (b instanceof JLabel) {
            t = t &amp;&amp; labels.add(b);
        }
    }
    return t;
}

The first method will actually not compile UNLESS you add an appropriate type parameter to the enclosing class, whereas the second method WILL compile regardless of whether the enclosing class has a type parameter. If you do not use <?>, then you are locally responsible for telling the compiler how to acquire the type that will be filled in by the letter used in its place. You frequently encounter this problem – needing to use ? rather than T – when attempting to write generic methods that use or need “extends” and “super.” A better but more elaborate treatment of this issue is on page 18 of Gilad Bracha’s Generics Tutorial (PDF). Also see this stack overflow question whose answer illuminates these issues.

Check out this stack overflow link for information about your second question: Java generics – type erasure – when and what happens. While I don’t know the answer to your question about the compile time difference between <?> and <T>, I’m pretty sure the answer can be found at this FAQ that erickson mentioned in that post.

Reference :

Initialize single dimensional and Multi-dimensional array and printing it

package com.demo2;

import java.util.Arrays;
import java.util.stream.Stream;

public class ArrayDemo {
	public static void main(String[] args) {
		int[] x = new int[10];
		int[][] y = new int[10][2];
		
		
		int[] x1 = {1,2,3};
		int[][] y1 = {
				{1,2},{3,4},{5,6}
		};
		
		Arrays.stream(x1).forEach(System.out::println);
		System.out.println("==========================================");
		Arrays.stream(y1).flatMapToInt(y2 -> Arrays.stream(y2)).forEach(System.out::println);
		System.out.println("==========================================");
		Stream.of(y1).flatMapToInt(y2 -> Arrays.stream(y2)).forEach(System.out::println);
		System.out.println("==========================================");
		for(int i=0;i<y1.length;i++) {
			int[] temp = y1[i];
			for(int j=0;j<temp.length;j++) {
				System.out.println(temp[j]);
			}
		}
	}
}

Collections with Generics

Quick Reference

  • Polymorphism is applicable only for base type but not for type parameter
  • Primitive cannot be passed as type parameter only object reference is allowed

Which of them works ?

  • ArrayList<String> l = new ArrayList<String>();
    • Valid-Polymorphism on Base Type ArrayList
  • List<String> l = new ArrayList<String>();
    • Valid-Polymorphism on Base Type List
  • Collection<String> l = new ArrayList<String>();
    • Valid-Polymorphism on Base Type Collection
  • ArrayList<Object> l = new ArrayList<String>();
    • Invalid-Polymorphism on parameter type
    • (Compile Time Error : Incompactable Types found ArrayList<String> required ArrayList<Object>)

Conclusion 1: Usage of parent reference to hold child object is the concept of polymorphism but it does not apply for type parameter

  • ArrayList<int> l = new ArrayList<int>();
    • Compile Time Error : Unexpected type found int required reference.

Conclusion 2 : For Type parameter we can provide any class or interface name but not primitives.

Generic Class

How to write a Generic Class?

  • Generic is identified by <T>, it is not necessary to be T but any alphabets. We take T commonly in the examples to suggest T as Types
  • If a Data Member(not member function) is a class uses a Generic Data member then its class name show be followed by name of the generic types inside an diamond operator.

Example :

class GenericClass<A,B,C>{
	A varA;
	B varB;
	C varC;
}

Example : On how a single classes variable can store different datatype

package com.test;

public class Demo {
	public static void main(String[] args) {
		Test<String> stringTest = new Test<>();
		stringTest.setItem("Hello");
		System.out.println(stringTest);
		Test<Integer> intTest = new Test<>();
		intTest.setItem(50);
		System.out.println(intTest);
		Test<Double> doubleTest = new Test<>();
		doubleTest.setItem(50.55);
		System.out.println(doubleTest);
		
	}
}
class Test<T>{
	T item;

	public T getItem() {
		return item;
	}

	public void setItem(T item) {
		this.item = item;
	}
	@Override
	public String toString() {
		return this.item.toString();
	}
}

Example : Multiple Parameters

package com.test;

public class DemoHashTable {
	public static void main(String[] args) {
		Hashtable<String,Integer> h1 = new Hashtable<>("Ten",10);
		System.out.println(h1);
		
		Hashtable<String,String> h2 = new Hashtable<>("Ten","Ten");
		System.out.println(h2);
	}
}
class Hashtable<K,V>{
	private K k;
	private V v;
	Hashtable(K k,V v){
		this.k = k;
		this.v = v;
	}
	@Override
	public String toString(){
		return k.toString()+" - "+v.toString();
	}
}

  • K – Key
  • E – Element
  • N – Number
  • T – Type
  • V – Value
  • S,U,V – Multiple Type

Spring Boot Exception Handling @ExceptionHandler and @ControllerAdvice

Spring 3.2 brings support for a global @ExceptionHandler with the @ControllerAdvice annotation.

This enables a mechanism that breaks away from the older MVC model and makes use of ResponseEntity along with the type safety and flexibility of @ExceptionHandler:

@ControllerAdvice
public class RestResponseEntityExceptionHandler 
  extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value 
      = { IllegalArgumentException.class, IllegalStateException.class })
    protected ResponseEntity<Object> handleConflict(
      RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, 
          new HttpHeaders(), HttpStatus.CONFLICT, request);
    }
}

The@ControllerAdvice annotation allows us to consolidate our multiple, scattered @ExceptionHandlers from before into a single, global error handling component.

The actual mechanism is extremely simple but also very flexible:

  • It gives us full control over the body of the response as well as the status code.
  • It provides mapping of several exceptions to the same method, to be handled together.
  • It makes good use of the newer RESTful ResposeEntity response.

One thing to keep in mind here is to match the exceptions declared with @ExceptionHandler to the exception used as the argument of the method.

If these don’t match, the compiler will not complain — no reason it should — and Spring will not complain either.

However, when the exception is actually thrown at runtime, the exception resolving mechanism will fail with:

java.lang.IllegalStateException: No suitable resolver for argument [0] [type=...]
HandlerMethod details: ...

Reference :

FailFast vs FailSafe Iterator

Iterators in java are used to iterate over the Collection objects.Fail-Fast iterators immediately throw ConcurrentModificationException if there is structural modification of the collection. Structural modification means adding, removing any element from collection while a thread is iterating over that collection. Iterator on ArrayList, HashMap classes are some examples of fail-fast Iterator.
Fail-Safe iterators don’t throw any exceptions if a collection is structurally modified while iterating over it. This is because, they operate on the clone of the collection, not on the original collection and that’s why they are called fail-safe iterators. Iterator on CopyOnWriteArrayList, ConcurrentHashMap classes are examples of fail-safe Iterator.

How Fail Fast Iterator works ?

To know whether the collection is structurally modified or not, fail-fast iterators use an internal flag called modCount which is updated each time a collection is modified.Fail-fast iterators checks the modCount flag whenever it gets the next value (i.e. using next() method), and if it finds that the modCount has been modified after this iterator has been created, it throws ConcurrentModificationException.

Important points of fail-fast iterators : 
 

  • These iterators throw ConcurrentModificationException if a collection is modified while iterating over it.
  • They use original collection to traverse over the elements of the collection.
  • These iterators don’t require extra memory.
  • Ex : Iterators returned by ArrayList, Vector, HashMap.

Note 1(from java-docs): The fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
Note 2 : If you remove an element via Iterator remove() method, exception will not be thrown. However, in case of removing via a particular collection remove() method, ConcurrentModificationException will be thrown. 

Fail Safe Iterator

First of all, there is no term as fail-safe given in many places as Java SE specifications does not use this term. I am using this term to demonstrate the difference between Fail Fast and Non-Fail Fast Iterator. These iterators make a copy of the internal collection (object array) and iterates over the copied collection. Any structural modification done to the iterator affects the copied collection, not original collection. So, original collection remains structurally unchanged
 

  • Fail-safe iterators allow modifications of a collection while iterating over it.
  • These iterators don’t throw any Exception if a collection is modified while iterating over it.
  • They use copy of original collection to traverse over the elements of the collection.
  • These iterators require extra memory for cloning of collection. Ex : ConcurrentHashMap, CopyOnWriteArrayList

Note(from java-docs) : The iterators returned by ConcurrentHashMap is weakly consistent. This means that this iterator can tolerate concurrent modification, traverses elements as they existed when iterator was constructed and may (but not guaranteed to) reflect modifications to the collection after the construction of the iterator.
 

Difference between Fail Fast Iterator and Fail Safe Iterator

The major difference is fail-safe iterator doesn’t throw any Exception, contrary to fail-fast Iterator.This is because they work on a clone of Collection instead of the original collection and that’s why they are called as the fail-safe iterator.


 

CyclicBarrier

The java.util.concurrent.CyclicBarrier class is a synchronization mechanism that can synchronize threads progressing through some algorithm. In other words, it is a barrier that all threads must wait at, until all threads reach it, before any of the threads can continue. Here is a diagram illustrating that:

Two threads waiting for each other at CyclicBarriers.
Two threads waiting for each other at CyclicBarriers.

The threads wait for each other by calling the await() method on the CyclicBarrier. Once N threads are waiting at the CyclicBarrier, all threads are released and can continue running.

Creating a CyclicBarrier

When you create a CyclicBarrier you specify how many threads are to wait at it, before releasing them. Here is how you create a CyclicBarrier:

CyclicBarrier barrier = new CyclicBarrier(2);

Waiting at a CyclicBarrier

Here is how a thread waits at a CyclicBarrier:

barrier.await();

You can also specify a timeout for the waiting thread. When the timeout has passed the thread is also released, even if not all N threads are waiting at the CyclicBarrier. Here is how you specify a timeout:

barrier.await(10, TimeUnit.SECONDS);

The waiting threads waits at the CyclicBarrier until either:

  • The last thread arrives (calls await() )
  • The thread is interrupted by another thread (another thread calls its interrupt() method)
  • Another waiting thread is interrupted
  • Another waiting thread times out while waiting at the CyclicBarrier
  • The CyclicBarrier.reset() method is called by some external thread.

CyclicBarrier Action

The CyclicBarrier supports a barrier action, which is a Runnable that is executed once the last thread arrives. You pass the Runnable barrier action to the CyclicBarrier in its constructor, like this:

Runnable      barrierAction = ... ;
CyclicBarrier barrier       = new CyclicBarrier(2, barrierAction);

CyclicBarrier Example

Here is a code example that shows you how to use a CyclicBarrier:

Runnable barrier1Action = new Runnable() {
    public void run() {
        System.out.println("BarrierAction 1 executed ");
    }
};
Runnable barrier2Action = new Runnable() {
    public void run() {
        System.out.println("BarrierAction 2 executed ");
    }
};

CyclicBarrier barrier1 = new CyclicBarrier(2, barrier1Action);
CyclicBarrier barrier2 = new CyclicBarrier(2, barrier2Action);

CyclicBarrierRunnable barrierRunnable1 =
        new CyclicBarrierRunnable(barrier1, barrier2);

CyclicBarrierRunnable barrierRunnable2 =
        new CyclicBarrierRunnable(barrier1, barrier2);

new Thread(barrierRunnable1).start();
new Thread(barrierRunnable2).start();

Here is the CyclicBarrierRunnable class:

public class CyclicBarrierRunnable implements Runnable{

    CyclicBarrier barrier1 = null;
    CyclicBarrier barrier2 = null;

    public CyclicBarrierRunnable(
            CyclicBarrier barrier1,
            CyclicBarrier barrier2) {

        this.barrier1 = barrier1;
        this.barrier2 = barrier2;
    }

    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() +
                                " waiting at barrier 1");
            this.barrier1.await();

            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() +
                                " waiting at barrier 2");
            this.barrier2.await();

            System.out.println(Thread.currentThread().getName() +
                                " done!");

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}

Here is the console output for an execution of the above code. Note that the sequence in which the threads gets to write to the console may vary from execution to execution. Sometimes Thread-0 prints first, sometimes Thread-1 prints first etc.

Thread-0 waiting at barrier 1
Thread-1 waiting at barrier 1
BarrierAction 1 executed
Thread-1 waiting at barrier 2
Thread-0 waiting at barrier 2
BarrierAction 2 executed
Thread-0 done!
Thread-1 done!