Tuesday 8 December 2015

New features in Java 9

New features in Java 9

Java 8 described as the major release of lambdas, streams and API changes, then Java 9 is all about Jigsaw, extra utilities and changes under the hood.

http://blog.takipi.com/java-9-the-ultimate-feature-list/

1. Java + REPL = jshell

The next release of Java will feature a new command line tool called jshell. It will Java way to REPL (Read-Eval-Print-Loop). 
REPL = If you’ll want to run a few lines of Java on their own you can run is as command prompt. you don’t have to wrap it all in a separate project or method. you don't required to use even semicolons.
?
1
2
3
-> 2 + 2
| Expression value is: 4
|     assigned to temporary variable $1 of type int

2. Microbenchmarks

The Java Microbenchmarking Harness (JMH) is a Java harness for building, running, and analyzing nano/micro/milli/macro benchmarks. When it comes to accurate benchmarking, there are forces in play like warm up times and optimizations that can have a big impact on results. Especially when you’re going down to micro and nano seconds.
JMH is your best choice if you want to get the most accurate results to help you reach the right decision following your benchmarks – And now it’s becoming a synonym with Java 9.

3. G1 be the new default garbage collector

With Java 9, There’s a running proposal that’s still in debate to replace the default garbage collector (The parallel / Throughput collector) with G1 which was introduced in Java 7.
Generally, G1 was designed to better support heaps larger than 4GB and has been known to cause less frequent GC pauses, but when a pause do comes, it tends to be longer.

4. HTTP 2.0 is the future

The official HTTP 2.0 RFC was approved just a few months ago, building on top of Google’s SPDY algorithm. SPDY has already shown great speed improvements over HTTP 1.1 ranging between 11.81% to 47.7% and its implementation already exists in most modern browsers.
Java 9 will have full support for HTTP 2.0 and feature a new HTTP client for Java that will replace HttpURLConnection, and also implement HTTP 2.0 and websockets.

5. The process API just got a huge boost

So far there has been a limited ability for controlling and managing operating system processes with Java. For example, in order to do something as simple as get your process PID in earlier versions of Java, you would need to either access native code or use some sort of a magical workaround. Moreover, it would require a different implementation for each platform to guarantee you’re getting the right result.

public static void main(String[] args) throws Exception
{
Process proc = Runtime.getRuntime().exec(new String[]{ "/bin/sh", "-c", "echo $PPID" });
if (proc.waitFor() == 0)
{
InputStream in = proc.getInputStream();
int available = in.available();
byte[] outputBytes = new byte[available];
in.read(outputBytes);
String pid = new String(outputBytes);
System.out.println("Your pid is " + pid);
}
}
In Java 9, expect the code for retrieving Linux PIDs, that now looks like this:

System.out.println("Your pid is " + Process.getCurrentPid())

The update will extend Java’s ability to to interact with the operating system: New direct methods to handle PIDs, process names and states, and ability to enumerate JVMs and processes and more.

6. Debugging in Production

Solving errors in production has always been a messy practice, grepping for clues over huge log files, and trying to identify the state that caused each exception or logged error. But what if you could avoid logs altogether? Here’s how it’s done.

7. A standardized lightweight JSON API

On a survey we conducted with 350 developers, the JSON API was just as hyped as Jigsaw but looks like it didn’t make the cut due to funding issues. Mark Reinhold, chief architect of the Java platform, on the JDK 9 mailing list:
“This JEP would be a useful addition to the platform but, in the grand scheme of things, it’s not as important as the other features that Oracle is funding, or considering funding, for JDK 9. We may reconsider this JEP for JDK 10 or a later release. ”

8. Money and Currency API

In other news, it also looks like the expected Money and Currency API is also lacking Oracle support. This is the answer we got from Anatole Tresch, the APIs spec lead:


New features in Java 8

JAVA 9 Schedule

proposed schedule for JAVA 9

JAVA 9 is scheduled for September 2016.

2015-12-10 – Feature Complete – All features implemented and integrated into the master forest
2016-02-04 – All Tests Run – All planned tests have been run on all supported platforms
2016-02-25 – Rampdown Start – Increased level of scrutiny is applied to incoming changes
2016-04-21 – Zero Bug Bounce – The bug backlog is completely addressed
2016-06-16 – Ramp down Phase 2 – A second round of checks is applied to incoming changes
2016-07-21 – Final Release Candidate – The final release candidate has been declared and submitted for testing
2016-09-22 – General Availability – Final release, ready for production use

More Info
New features in Java 9
New features in Java 8

Tuesday 24 November 2015

Java Annotations Tutorial and Example

What is Java Annotations & How to Create It?

Java annotations are used to provide meta data for your Java code. Being meta data, Java annotations do not directly affect the execution of your code. These annotations can then be processed at compile time by pre-compiler tools, or at runtime via Java Reflection.

Classes, methods, variables, parameters and packages may be annotated. 

Some Built-in Java Annotations

  • @Override - Checks that the method is an override. Causes a compile error if the method is not found in one of the parent classes or implemented interfaces.
  • @Deprecated - Marks the method as obsolete. Causes a compile warning if the method is used.
  • @SuppressWarnings - Instructs the compiler to suppress the compile time warnings specified in the annotation parameters.

Java Annotation Types

  1. Build-time instruction (Development time) - Retention is set to source only, such annotation are use full at source level only and removed by compiler while generating binary class file.
    e.g. @Documented
  2. Compiler  instructions (Deployment time) - Retention is set be to class only. Such annotation are used by compiler or deployment tools for taking some specific action e.g. producing compile time error in case of some rule or guideline violation.
    e.g. @Depricated, @Override
  3. Runtime instructions (Execution time) - Retention is set run-time, such annotation are retained in class file are used for deducing some meta information at run time and may effect run time processing. These annotations are not ignored by VM.
    e.g. @Entity, @Test

Use cases

Annotations can be used for many different purposes, the most common ones are:
  • Information for the compiler - Annotations can be used by the compiler to produce warnings or even errors based on different rules. One example of this kind of usage is the Java 8 @FunctionalInterface annotation. This one makes the compiler to validate the annotated class and check if it is a correct functional interface or not.
  • Documentation - Annotations can be used by software applications to measure the quality of the code like FindBugs or PMD do or generate reports automatically like Jenkins, Jira or Teamcity.
  • Code generation - annotations can be used to generate code or XML files automatically using metadata information present in the code. A good example of this is the JAXB library.
  • Runtime processing - Annotations that are examined in runtime can be used for different objectives like unit testing (Junit), dependency injection (Spring), validation, logging (Log4J) ,data access (Hibernate) etc.

Creating Custom Annotation

Rules of Thumb for Defining Java Annotation Types

Here are some rules-of-thumb when defining an annotation type:
  1. Annotation declaration should start with an 'at' sign like @, following with an interface keyword, following with the annotation name.
  2. Method declarations should not have any parameters.
  3. Method declarations should not have any throws clauses.
  4. Return types of the method should be one of the following:
    • primitives
    • String
    • Class
    • enum
    • array of the above types

The Java reflection API

  • getAnnotations(): Returns all annotations for the given element, also the ones that are not explicitly defined in the element definition.
  • isAnnotationPresent(annotation): Checks if the passed annotation in available or not in the current element.
  • getAnnotation(class): Retrieves an specific annotation passed as parameter. Returns null if this annotation is not present for the given element.
This class is implementing by java.lang.Classjava.lang.reflect.Method and java.lang.reflect.Field among others, so can be used basically with any kind of Java element.

RetentionPolicy:
 CLASS:Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.
 RUNTIME:Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.
 SOURCE: Annotations are to be discarded by the compiler.

Create Custom Annotation Example

Define new custom annotation


@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface CustomAnnotationMethod {
public String author() default "danibuiza";
public String date();
public String description();

Use on Class or Method

@CustomAnnotationClass( date = "2014-05-05" )
public class AnnotatedClass {

@CustomAnnotationMethod( date = "2014-06-05", description = "annotated method" )
public String annotatedMethod() {
return "nothing niente";
}
}

Write a program to Process Annotations


public static void main(String[] args) throws Exception {
Class < AnnotatedClass > object = AnnotatedClass.class;
// Retrieve all annotations from the class
Annotation[] annotations = object.getAnnotations();
for (Annotation annotation: annotations) {
System.out.println(annotation);
}

// Checks if an annotation is present
if (object.isAnnotationPresent(CustomAnnotationClass.class)) {
// Gets the desired annotation
Annotation annotation = object.getAnnotation(CustomAnnotationClass.class);
System.out.println(annotation);
}
// the same for all methods of the class
for (Method method: object.getDeclaredMethods()) {
if (method.isAnnotationPresent(CustomAnnotationMethod.class)) {
Annotation annotation = method.getAnnotation(CustomAnnotationMethod.class);
System.out.println(annotation);
}
}
}

Thursday 19 November 2015

Improve Software Quality

Improve Software Quality= Development Improvement + Management Improvement


Development Improvement

1. Get the Requirements Right
               Impact on Quality: Meet business requirements; achieve a satisfying user experience.
               Benefit: Less rework means less retesting and fewer cycles, which greatly reduces the overall effort.
              
2. Design Applications to Lessen Bug Risk
               Impact on Quality: Reduce defects.
               Benefit: Simpler, cleaner designs result in code that is simpler, cleaner, and easier to test and rework.
              
3. Implement Best Practices, Follow Design Patterns & Principles, Increase Reusability
               Impact on Quality: Improves Quality and Performance
               Benefit: Decreases unexpected bugs. Best Practices and Design Principle improves skills, reduces waste and improves quality. Fast development & thus Developers/Managers could give more time about Quality and user experience.
              
4. Test Smarter to Test Less & Optimize the Use of Testing Tools
               Impact on Quality: Reduce defects.
               Benefit: A focus at risk areas on testing the most crucial. Automation frees resources from mundane testing to focus on the highest-priority tests and increases test cycles' repeatability.


Management Improvement

1. Fine-Tune Team/Individual Goals to Include Quality
               Impact on Quality: Meet business requirements; achieve a satisfying user experience; reduce defects.
               Benefit:Team members perform according to their incentives, making quality improvement part of their goals reinforces desirable behavior.
              
2. Define Quality and Broadcast Simple Quality Metrics
               Impact on Quality: Achieve a satisfying user experience. Increases Quality
               Benefit: Highly visible metrics keep quality top of mind for the entire team and expose when efforts fall short.
              
3. Reuse Knowledge and Experience
               Impact on Quality: Reduce defects.
               Benefit: Reusing ideas, documents, and expertise avoids making the same mistakes again. Makes the organization's best problem-solving experiences reusable.

4. Continues Feedbacks
               Impact on Quality: Improves Quality and User experience.
               Benefit: Whatever has been learned about the product, the processes that produced it, or any other feedback will improve improves Quality and User experience.

Wednesday 18 November 2015

New features in Java 8

Java 8 included following new Features.

    1. Lambda expressions
    2. Method references
    3. Default Methods (Defender methods)
    4. A new Stream API (Parallel operations)
    5. Optional Class
    6. A new Date/Time API
    7. Nashorn, the new JavaScript engine (Java + JavaScript)
    8. Removal of the Permanent Generation
    9. Other New Features

1. Lambda Expressions

The biggest new feature of Java 8 is language level support for lambda expressions (Project Lambda). Java lambda expressions are Java's first step into functional programming. A Java lambda expression is thus a function which can be created without belonging to any class. A lambda expression can be passed around as if it was an object and executed on demand.

Following are the important characteristics of a lambda expression

    • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
    • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
    • Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
    • Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.

syntax: 

parameter -> expression body

Examples:


1. With type declaration

MathOperation addition = (int a, int b) -> a + b;  

2. With out type declaration

MathOperation subtraction = (a, b) -> a - b;  

3. With return statement along with curly braces

MathOperation multiplication = (int a, int b) -> { return a * b; };  
4. Without return statement and without curly braces
MathOperation division = (int a, int b) -> a / b;


More Info

2. Method references(Parallel operations)


You use lambda expressions to create anonymous methods. Method references help to point to methods by their names. A method reference is described using :: (double colon) symbol.
You can use replace Lambda Expressions with Method References where Lamdba is invoking already defined methods.
You can’t pass arguments to methods Reference

There are four kinds of method references:

  1. Reference to a static method  ContainingClass::staticMethodName
  2. Reference to an instance method of a particular object
    containingObject::instanceMethodName
  3. Reference to an instance method of an arbitrary object of a particular type
    ContainingType::methodName
  4. Reference to a constructor ClassName::new

Example:

List names = new ArrayList();

names.add("Mahesh");
names.add("Suresh");
names.add("Ramesh");
names.add("Naresh");
names.add("Kalpesh");


names.forEach(System.out::println);


More Info

3. Default Methods (Defender methods)

Default methods can be provided to an interface without affecting implementing classes as it includes an implementation just by adding the keyword default before the method’s access modifier.
Modify one interface in JDK framework breaks all classes that extends the interface. Default methods enable us to add new or default functionalities/behavior to existing interfaces without breaking the classes that implements that interface.
After introducing Default Method, it seems that interfaces and abstract classes are same. However, they are still different concept in Java 8.

Example:


public interface vehicle {

  default void print(){

 System.out.println("I am a vehicle!");

  }

}
4. A new Stream API.
Don't confuse with InputStream and OutputStream from Java I/O. This is Completely different thing. Streams adhere to a common Pipes and Filters software pattern.

A Stream is a free flowing sequence of elements. They do not hold any storage as that responsibility lies with collections such as arrays, lists and sets. Every stream starts with a source of data, sets up a pipeline, processes the elements through a pipeline and finishes with a terminal operation. They allow us to parallelize the load that comes with heavy operations without having to write any parallel code. A new package java.util.stream was introduced in Java 8 to deal with this feature.

Example:

List<String>  myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);

Deeper Look at Streams

The Stream interface is defined in java.util.stream package. Starting from Java 8, the java collections will start having methods that return Stream. This is possible because of another cool feature of Java 8, which is default methods. Streams can be defiled as a sequence of elements from a source that supports aggregate operations.
The source here refers to a Collection, IO Operation or Arrays who provides data to a Stream. Stream keeps the order of the data as it is in the source. Just like functional programming languages, Streams support Aggregate Operations. The common aggregate operations are filter, map, reduce, find, match, sort. These operations can be executed in series or in parallel.

The Streams also support Pipelining and Internal Iterations. The Java 8 Streams are designed in such a way that most of its stream operations returns Streams only. This help us creating chain of various stream operations. This is called as pipelining. The pipelined operations looks similar to a sql query.


5. Optional Class


Optional is a new container type that wraps a single value, if the value is available. So it's meant to convey the meaning that the value might be absent. 

Optional is an attempt to reduce the number of null pointer exceptions in Java systems, by adding the possibility to build more expressive APIs that account for the possibility that sometimes return values are missing. By using Optional, and never working with null, you could avoid null checks altogether.

Example:


public Optional<String> getOptionalNullString(){

 return(null);

}

java.util.Optional is a container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

More Info


6. A new Date/Time API

Working with New Date and Time objects


By default LocalDate/Time classes will use the system clock in the default time zone. We can change this by providing a time zone or an alternative Clock implementation.


They are also coming with better time zone support with ZoneOffSet, ZoneId, ZonedDateTime or OffsetDateTime. 
Parsing and Formatting of Dates are also revamped with new DateTimeFormatter class.
Clock, which can be used to get current instant, date and time using time zone.

Deeper Look at Date/Time API

New date and time API is located inside java.time package and some of the key classes are following.
Instant - Represents a timestamp
LocalDate - Represents a year-month-day date without time.
LocalTime - Represents a time without dates.
LocalDateTime - Combines date and time in one class.
We can use the plus and minus methods to add or subtract specific amounts of time. Note that these methods always return a new instance (Java 8 date/time classes are immutable).

Example:

LocalDate tomorrow = LocalDate.now().plusDays(1);
Some information can be obtained without providing a specific date. For example, we can use the Year class if we need information about a specific year:

Example:

Year currentYear = Year.now();
  boolean isLeap = currentYear.isLeap();
Timestamps
  Classes like LocalDate and ZonedDateTime provide a human view on time. However, often we need to work with time viewed from a machine perspective. For this we can use the Instant class which represents timestamps. 

Example:

  Instant now = Instant.now(); // current time
  Instant fromUnixTimestamp = Instant.ofEpochSecond(1262347200); // from unix timestamp, 2010-01-01 12:00:00
  Instant fromEpochMilli = Instant.ofEpochMilli(1262347200000l); // same time in millis 
Periods and Durations
  Period and Duration are two other important classes. Like the names suggest they represent a quantity or amount of time. A Period uses date based values (years, months, days) while a Duration uses seconds or nanoseconds to define an amount of time.

Example:

  LocalDate firstDate = LocalDate.of(2010, 5, 17); // 2010-05-17
  LocalDate secondDate = LocalDate.of(2015, 3, 7); // 2015-03-07
  Period period = Period.between(firstDate, secondDate);

  Instant firstInstant= Instant.ofEpochSecond( 1294881180 ); // 2011-01-13 01:13
  Instant secondInstant = Instant.ofEpochSecond(1294708260);
  Duration between = Duration.between(firstInstant, secondInstant);
More Info 
More Examples

7. Nashorn, the new JavaScript engine (Java + JavaScript)


Nashorn is a JavaScript engine for the JVM that is released with Java 8. It has replaced the existing Rhino engine.



As JavaScript is getting popular on server-side programming (like Node.js).

The Nashorn javascript engine can either be used pragmatically from java programs or by utilizing the command line tool jjs, which is located in $JAVA_HOME/bin. If you plan to work with jjs you might want to put a symbolic link for simple access:

Example 1:


$  jjs -scripting heredocs.js

Example 2:

ScriptEngineManager engineManager =  new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("nashorn");
engine.eval(new FileReader("src/sample2/mustache.js"));
engine.eval("print('Hello World!');");

8. Removal of the Permanent Generation

Permanent Generation memory space is completely removed.
The good news is that it means no more java.lang.OutOfMemoryError: PermGen space problems and no need for you to tune and monitor this memory space any more.

Impact:

The PermSize and MaxPermSize JVM arguments are ignored and a warning is issued if present at start-up.
Metaspace: A new memory space is born.
More Info

9. Other New Features

Concurrent accumulators

One of the most common scenarios in concurrent programming is updating of numeric counters accessed by multiple threads.

Parallel operations

You can think of this as an extension of iterators where the actual operation of extracting the next item from a collection on which to operate is carried out by an iterator. An exciting possibility opened by this design pattern is to enable operations carried out on long arrays such as sorting, filtering and mapping to be carried out in parallel by the framework. 

String.join

String abc= String.join(" ", "Java", "8");

Type Annotations

List<@Nullable String>
@NotNull String[] arr;
new @NonEmpty @Readonly List(myNonEmptyStringSet)
new @Interned MyObject()

Functional Interfaces

java.util.function

Stamped Locks

The problem is that the ReadWriteLock can be super slow (up to 10x), which kind of defeats its purpose. Java 8 introduces a new ReadWrite lock – called StampedLock.

Controlling OS Processes

Launching an OS process from within your code is right there with JNI calls – it’s something you do half-knowing there’s a good chance you’re going to get some unexpected results and some really bad exceptions down the line.

Exact Numeric Operations

Math class geared towards protecting sensitive code from implicit overflows, by throwing an unchecked ArithmeticException when the value of an operation overflows its precision.
int safeC = Math.multiplyExact(bigA, bigB); // will throw ArithmeticException if result exceeds +-2^31

Secure Random Generation

Java 8 has added a new method called SecureRandom.getInstanceStrong() whose aim is to have the JVM choose a secure provider for you.

References


Other Milestones Completed
New Features in Java SE 8 PPT
8 Great Java 8 Features
Video: New Features in Java SE 8
JDK 8 Features