Java 8

Revision as of 07:29, 11 July 2018 by Rasimsen (talk | contribs) (StreamAPI - Parallelism)

What are the new features introduced in JAVA 8?

There are dozens of features added to Java 8, the most significant ones are mentioned below −

  • Lambda expression − Adds functional processing capability to Java.
  • Method references − Referencing functions by their names instead of invoking them directly. Using functions as parameter.
  • Default method − Interface to have default method implementation.
  • New tools − New compiler tools and utilities are added like 'jdeps' to figure out dependencies.
  • Stream API − New stream API to facilitate pipeline processing.
  • Date Time API − Improved date time API.
  • Optional − Emphasis on best practices to handle null values properly.
  • Nashorn, JavaScript Engine − A Java-based engine to execute JavaScript code.

Along with these new featuers, lots of feature enhancements are done under-the-hood, at both compiler and JVM level.

StreamAPI - Parallelism

Parallel computing involves dividing a problem into subproblems, solving those problems simultaneously (in parallel, with each subproblem running in a separate thread), and then combining the results of the solutions to the subproblems.

One difficulty in implementing parallelism in applications that use collections is that collections are not thread-safe, which means that multiple threads cannot manipulate a collection without introducing thread interference or memory consistency errors. The Collections Framework provides synchronization wrappers, which add automatic synchronization to an arbitrary collection, making it thread-safe. However, synchronization introduces thread contention. You want to avoid thread contention because it prevents threads from running in parallel. Aggregate operations and parallel streams enable you to implement parallelism with non-thread-safe collections provided that you do not modify the collection while you are operating on it.

Note that parallelism is not automatically faster than performing operations serially, although it can be if you have enough data and processor cores. While aggregate operations enable you to more easily implement parallelism, it is still your responsibility to determine if your application is suitable for parallelism.


private long countPrimes(int max) {
    return range(1, max).parallel().filter(this::isPrime).count();
}
private boolean isPrime(long n) {
    return n > 1 && rangeClosed(2, (long) sqrt(n)).noneMatch(divisor -> n % divisor == 0);
}
private List<StockInfo> getStockInfo(Stream<String> symbols) {
     return symbols.parallel()
            .map(this::getStockInfo) //slow network operation
            .collect(toList());
}

Executing Streams in Parallel

Concurrent Reduction

Ordering

Side Effects

Laziness

Interference

Stateful Lambda Expressions

Java with Questions

What are default methods?

With java 8, an interface can have default implementation of a function in interfaces.

What are static default methods?

An interface can also have static helper methods from Java 8 onwards.

public interface vehicle {
   default void print() {
      System.out.println("I am a vehicle!");
   }
 
   static void blowHorn() {
      System.out.println("Blowing horn!!!");
   }
}


How will you call a default method of an interface in a class?

Using super keyword along with interface name.

interface Vehicle {
   default void print() {
      System.out.println("I am a vehicle!");
   }
}
class Car implements Vehicle {
   public void print() {
      Vehicle.super.print();                  
   }
}

How will you call a static method of an interface in a class?

Using name of the interface.

interface Vehicle {
   static void blowHorn() {
      System.out.println("Blowing horn!!!");
   }
}
class Car implements Vehicle {
   public void print() {
      Vehicle.blowHorn();                  
   }
}

What is streams in Java 8?

Stream represents a sequence of objects from a source, which supports aggregate operations.

What is stream pipelining in Java 8?

Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream.

What is the difference between Collections and Stream in Java8 ?

Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required.

What is Parallel Processing in Java 8?

parallelStream is the alternative of stream for parallel processing. Take a look at the following code segment that prints a count of empty strings using parallelStream.

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
//get count of empty string
int count = strings.parallelStream().filter(string > string.isEmpty()).count();
//It is very easy to switch between sequential and parallel streams.

What are collectors in Java 8?

Collectors are used to combine the result of processing on the elements of a stream. Collectors can be used to return a list or a string.

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
System.out.println("Filtered List: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("Merged String: " + mergedString);

What are Statistics collectors in Java 8?

With Java 8, statistics collectors are introduced to calculate all statistics when stream processing is being done.

Following code will print the highest number present in a list.

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = integers.stream().mapToInt((x) > x).summaryStatistics();
System.out.println("Highest number in List : " + stats.getMax());

What is Optional in Java8?

Optional is a container object which is used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava.

What is Nashorn in Java8?

With Java 8, Nashorn, a much improved javascript engine is introduced, to replace the existing Rhino. Nashorn provides 2 to 10 times better performance, as it directly compiles the code in memory and passes the bytecode to JVM. Nashorn uses invokedynamics feature, introduced in Java 7 to improve performance.

What is jjs in JAVA8?

For Nashorn engine, JAVA 8 introduces a new command line tool, jjs, to execute javascript codes at console.

Can you execute javascript code from java 8 code base?

Yes! Using ScriptEngineManager, JavaScript code can be called and interpreted in Java.

What is local datetime API in JAVA8?

Local − Simplified date-time API with no complexity of timezone handling.