Sunday, April 2, 2017

Java 7 Features

  • Binary Literals  - In Java SE 7, the integral types (byteshortint, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number.
Before:
public void testBinaryIntegralLiterals(){
        int binary = 8;
        if (binary == 8){
            System.out.println(true);
        } else{
            System.out.println(false);
        }
}
Java7:
public void testBinaryIntegralLiterals(){
        int binary = 0b1000; //2^3 = 8
        if (binary == 8){
            System.out.println(true);
        } else{
            System.out.println(false);
        }
}

  • Underscores in Numeric Literals - Any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.
public void testUnderscoresNumericLiterals() {
    int oneMillion_ = 1_000_000; //new
    int oneMillion = 1000000;
    if (oneMillion_ == oneMillion){
        System.out.println(true);
    } else{
        System.out.println(false);
    }
}

Before:
public void testStringInSwitch(String param){
       final String JAVA5 = "Java 5";
       final String JAVA6 = "Java 6";
       final String JAVA7 = "Java 7";
       if (param.equals(JAVA5)){
           System.out.println(JAVA5);
       } else if (param.equals(JAVA6)){
           System.out.println(JAVA6);
       } else if (param.equals(JAVA7)){
           System.out.println(JAVA7);
       }
   }
Java7:
public void testStringInSwitch(String param){
       final String JAVA5 = "Java 5";
       final String JAVA6 = "Java 6";
       final String JAVA7 = "Java 7";
       switch (param) {
           case JAVA5:
               System.out.println(JAVA5);
               break;
           case JAVA6:
               System.out.println(JAVA6);
               break;
           case JAVA7:
               System.out.println(JAVA7);
               break;
       }
   }

  • Type Inference for Generic Instance Creation (Diamond Operator) - You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.
Before:
public void testDinamond(){
    List list = new ArrayList();
    Map> map = new HashMap>();
}
Java7:
public void testDinamond(){
    List list = new ArrayList<>();
    Map> map = new HashMap<>();
}

  • The try-with-resources Statement - The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements the new java.lang.AutoCloseable interface or the java.io.Closeable interface can be used as a resource. The classes java.io.InputStreamOutputStreamReaderWriterjava.sql.ConnectionStatement, and ResultSet have been retrofitted to implement the AutoCloseable interface and can all be used as resources in a try-with-resources statement.

Before:
public void testTryWithResourcesStatement() throws FileNotFoundException, IOException{
     FileInputStream in = null;
    try {
        in = new FileInputStream("java7.txt");
        System.out.println(in.read());
    } finally {
        if (in != null) {
            in.close();
        }
    }
}
Java 7:
public void testTryWithResourcesStatement() throws FileNotFoundException, IOException{
    try (FileInputStream in = new FileInputStream("java7.txt")) {
        System.out.println(in.read());
    }
}




Before:
public void testMultiCatch(){
     try {
         throw new FileNotFoundException("FileNotFoundException");
     } catch (FileNotFoundException fnfo) {
         fnfo.printStackTrace();
     } catch (IOException ioe) {
         ioe.printStackTrace();
}
Java 7:
public void testMultiCatch(){
    try {
        throw new FileNotFoundException("FileNotFoundException");
    } catch (FileNotFoundException | IOException fnfo) {
        fnfo.printStackTrace();
    }
}




Java 1.6 Features - Collection Framework Enhancements

 
   Java 1.6 provides the better bi-directional collection access on collections framework.

   The following new interfaces are added in this version:

   i) Deque - It is a double ended queue, supporting element insertion and removal at both ends. It extends the Queue interface.
   ii) BlockingDeque - Its inheriting the feature of deque and performs the operations that wait for deque to become non-empty and wait for space to become available in the deque when storing elements.
   iii) NavigableSet - It may be accessed and traversed in either ascending and descending order.
   iv) NavigableMap - It may be accessed and traversed in either ascending and descending key order.
    V) ConcurrentNavigableMap - Its similar to NavigableMap and this interface is part of java.util.concurrent.

    The following classes have been added:

     i) ArrayDeque
    ii) ConcurrentSkiplistSet
   iii) ConcurrentSkipListMap
    iv) LinkedBlockingQueue
     v) AbstractMap.SimpleEntry
    vi) AbstratMap.SimpleImmutableEntry

Other than this Two new methods were added to the Collection Utility classes:

 1. newSetFromMap(Map) -- Create a Set implementaion from Map. There is no IdentitiHashSet class but instead, just use

Set<Object> identityHashSet = Collections.newSetFromMap(new IdentityHashMap<object, Boolean>());

2. asLifoQueue(Deque) - returns a view of a Deque as a Last-in-first-out (Lifo) Queue

The Arrays utility class now has methods copyOf and copyOfRange that can efficiently resize, truncate, or copy subarrays for arrays of all types.
Before:

int[] newArray = new int[newLength];
System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
After:

int[] newArray = Arrays.copyOf(a, newLength);

Which should you use, abstract classes or interfaces?

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.
Which should you use, abstract classes or interfaces?
  • Consider using abstract classes if any of these statements apply to your situation:
    • You want to share code among several closely related classes.
    • You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
    • You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
  • Consider using interfaces if any of these statements apply to your situation:
    • You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
    • You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
    • You want to take advantage of multiple inheritance of type.
An example of an abstract class in the JDK is AbstractMap, which is part of the Collections Framework. Its subclasses (which include HashMapTreeMap, and ConcurrentHashMap) share many methods (including getputisEmptycontainsKey, and containsValue) that AbstractMap defines.
An example of a class in the JDK that implements several interfaces is HashMap, which implements the interfaces SerializableCloneable, and Map<K, V>. By reading this list of interfaces, you can infer that an instance of HashMap (regardless of the developer or company who implemented the class) can be cloned, is serializable (which means that it can be converted into a byte stream; see the section Serializable Objects), and has the functionality of a map. In addition, the Map<K, V> interface has been enhanced with many default methods such as merge and forEach that older classes that have implemented this interface do not have to define.
Note that many software libraries use both abstract classes and interfaces; the HashMap class implements several interfaces and also extends the abstract class AbstractMap.

Limitation of synchronized keyword in Java

1. Synchronized keyword doesn't allow separate locks for reading and writing. As we know that multiple threads can read without affecting thread-safety of class, synchronized keyword suffer performance due to contention in case of multiple readers and one or few writer.

 2. If one thread is waiting for lock then there is no way to timeout, the thread can wait indefinitely for the lock.
 
3. On a similar note if the thread is waiting for the lock to acquired there is no way to interrupt the thread.
 
All these limitations of synchronized keyword are addressed and resolved by using ReadWriteLock and ReentrantLock in Java 5.

Private and Final Methods in java?

  • private methods cannot be overridden by subclasses
  • final methods cannot be overridden by subclasses
  • final methods allow for faster code when compiled with optimizations on (javac -O)
My questions are:
  1. Why not declare all private methods final as well?
  2. Do most compilers treat private methods as final?
A: As you point out, subclasses may not override private methods by design. Furthermore, the final keyword tells the compiler that subclasses may not override a method regardless of its access level. Since private already implies that a subclass may not override a method, declaring a private method to be final is redundant. Making the declaration won't cause problems, but it won't accomplish anything either, since privates are automatically considered final.
Well, the practice of declaring all private methods final will have one side effect. Any novice Java programmer who encounters your code will assimilate your usage of private final, thinking that privates must be declared in that manner. So, you'll be able to judge who has and who has not been in contact with your code. It might prove an interesting exercise.
So, to answer question 1, there is no need to declare private members final.
As for question 2, an optimizing compiler and JVM can take advantage of privatemethods and final methods. Since subclasses may not override those types, there is no need to do dynamic binding at runtime. Subclasses will never override the method, so the runtime will always know what method to call without searching up the inheritance hierarchy. During compilation an optimizing compiler may even choose to inline all private and final methods to improve performance.
So, to answer question 2, yes, all compilers will treat private methods as final. The compiler will not allow any private method to be overridden. Likewise, all compilers will prevent subclasses from overriding final methods.
A more interesting question: Will all compilers optimize finals and privates so that they are inline? The short answer is no. Optimization behavior will be dependent on the compiler and its settings.

When and where to use the Singleton Pattern?

Singletons are used in situations where we need access to a single set of data throughout
an application. 

For example, application configuration data and reusable data caches are
commonly implemented using singletons. Singletons may also be used to coordinate access

to shared resources, such as coordinating write access to a file.

Singleton pattern is used for logging, drivers objects, caching and thread pool.(in log4j,Hibernate we are using the this pattern)