Tuesday, August 11, 2015

Default Methods

Default Methods in Java 8

In my previous articles, we have looked at LambdaExpressions and Method References. In this latest article in the series, we will be looking at Default methods.


What is Default method?

Default methods enable us to add new functionalities to interfaces without breaking the classes that implements that interface.

We specify that a method definition in an interface is a default method with the default keyword at the beginning of the method signature. All method declarations in an interface, including default methods, are implicitly public, so you can omit the public modifier.

Extending Interfaces that contains default methods

When you extend an interface that contains a default method, you can do following:
  • Not mention the default method at all, which lets your extended interface inherit the default method.
  • Re declares the default method, which makes it abstract.
  • Redefine the default method, which overrides it.

Lamda Expression in Java 8


Lambda Expressions

Why Lambda in Java

Since beginning, the Java language always remained Object first language. Everthing should come after an Object After working with functional language like JavaScript, it becomes clear to one how Java enforce its strict object-oriented nature and strict typed on the source code.
You see Functions are not important for Java. On their own they cannot live in Java world.

Functions are first class citizens in a functional programming language. They exists on their own. You can assign them to a variable and pass them as arguments to other functions.
JavaScript is one of the best example of an FP language

Lambda expression adds that missing link of functional programming to Java. Lambda expression let us have functions as first class citizen. Although this is not 100% correct, we will shortly see how!

In Java, the lambda expressions are represented as objects, and so they must be bound to a particular object type known as a functional interface. We will see in detail about Functional interface here.

Lambda expressions can only appear in places where they will be assigned to a variable whose type is a functional interface.

Introduction to Lambda Expressions

As mentioned in the java docs 
One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear. In these cases, you're usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expressions enable you to do this, to treat functionality as method argument, or code as data. 

What is a Lambda Expression ?

Lambda expressions are anonymous methods, aimed at mainly addressing the Anonymous classes's syntax by replacing the machinery of anonymous inner classes with a lighter-weight mechanism in applicable cases.

Lambda Expressions enable you to encapsulate a single unit behaviour and pass it to other code.

Lambda expressions are supported by the following features:

Method References:
Method references are compact, easy-to-read lambda expressions for methods that already have a name.

Default Methods:
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older version of those interfaces. They are interface methods that have an implementation and default keyword at the beginning of method signature.

New and Enhanced APIs

In Java SE8, new classes have been introduced and existing classes have been enhanced to take advantage of lambda expressions and streams. We can find most of the new and enhances classes in following packages:

Java.util: An existing package in which we integrated Java Collection Framework with streams and provide general utility functionality used by streams.
 • Java.util.function: A new package that contains general purpose functional interfaces that provide target types for lambda expressions and method references.
 • Java.util.stream: A new package that contains the majority of interfaces and classes that provide functionality to streams and aggregate operations.

Modified Packages: All the Wrapper classes have been enhanced with methods that are suitable for target of method references. For example: Integer.sum





Method References

Method References in Java 8 


In my previous articles, we have looked at LambdaExpressions and Default methods. In this latest article in the series, we will be looking at Method References.

What  is Method References?
This feature is introduced in Java 8 for Lambda Expression. So it is but obvious that this is going to be used best with Lambda expressions.
Lambdas let us define anonymous methods and treat them as instances of functional interfaces.

Method references let us accomplish the same thing, but with existing methods. Method references are similar to lambdas in that they require a target type. However, instead of providing method implementations, they refer to the methods of existing classes or objects.
public class Employee {

    String name;
    LocalDate birthday;
    String emailAddress;

    public int getAge() {
        // ...
    }
   
    public Calendar getBirthday() {
        return birthday;
    }   

    public static int compareByAge(Person a, Person b) {
        return a.birthday.compareTo(b.birthday);
    }}

Let’s assume that we have an array of Employees as:
List  employeeList;
 
Employee [] employeeArray = employeeList.toArray(new Employee[employeeList.size()]);
Now if we need to sort them by their age we need to write a new comparator class as follows:
class EmployeeAgeComparator  implements Comparator 
{
  public int compare(Employee a, Employee b) {
  return a.getBirthday().compareTo(b.getBirthday());
}
}
Now we can call the sorting logic in following ways: 
//Without method reference
Arrays.sort(employeeArray, new EmployeeAgeComparator());
         
//With lambda expression
Arrays.sort(employeeArray,
            (Employee a, Employee b) -> {
                return a.getBirthday().compareTo(b.getBirthday());
            }
        );
         
//With method reference
Arrays.sort(employeeArray, Employee::compareByAge);

Wednesday, July 29, 2015

Functional Interfaces

Functional Interfaces

In single line description, Interface with only abstract method are referred as Functional Interface. However, A functional interface can have more than one static or default methods, and also can Override some methods from java.lang.Object

Luckily you do not need to verify the Functional Interface, Compiler will do it for you. But you can specify @FunctionalInterface annotation to reduce it’s workload.

Below is an example of Functional interface.
 interface Demo { 
    // Only abstract method. 
    void method1(Collection collection); 
    // Functional interface can have more than one static or default  methods. 

    default void method2() 
    { 
      System.out.println("This is default in Functional Interface."); 
    } // And also can override methods of java.lang.Object 
    @Override 
    public String toString(); 
     
  }

Some frequently used and popular Functional Interfaces are:  

  • java.awt.event.ActionListener;
  • java.lang.Runnable
  • java.util.concurrent.Callable
  • java.security.PrivilegedAction
  • java.util.Comparator
  • java.io.FileFilter
  • java.beans.PropertyChangeListener

Note :

A new package in Java 8 is added that contains functional interfaces that are commonly used for lambda expression and method reference : java.util.function 

Tuesday, July 28, 2015

scjp summary


Before we dig into class declarations, let's do a quick review of the rules associated with declaring classes,
  There can be only one public class per source code file.
Comments can appear at the beginning or end of any line in the source code file; they are independent of any of the positioning rules discussed here.
If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Dog { } must be in a source code file named Dog.java.
If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present.
the first line in the source code file.
If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn't a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements, the class declaration must be
import and package statements apply to all classes within a source code file. In other words, there's no way to declare multiple classes in a file and have them in different packages, or use different imports.

Class Declarations and Modifiers
Java is a package-centric language; the developers assumed that for good organization and name scoping, you would put all your classes into packages.
They were right, and you should. Imagine this nightmare: Three different programmers, in the same company but working on different parts of a project, write a class named Utilities. If those three Utilities classes have not been declared in any explicit package, and are in the classpath, you won't have any way to tell the compiler or JVM which of the three you're trying to reference. Sun recommends that developers use reverse domain names, appended with division and/or project names. For example, if your domain name is geeksanonymous.com, and you're working on the client code for the TwelvePointOSteps program, you would name your package something like com.geeksanonymous.steps.client. That would essentially change the name of your class to com.geeksanonymous.steps.client.Utilities. You might still have name collisions within your company, if you don't come up with your own naming schemes, but you're guaranteed not to collide with
classes developed outside your company (assuming they follow Sun's naming  convention, and if they don't, well, Really Bad Things could happen).
A file can have more than one nonpublic class.Files with no public classes can have a name that does not match any of the classes in the file.

import statements, and package statements in a source file:

Source File Declaration Rules

Friday, July 24, 2015

JVM

Summary on Garbage collection in Java


1) Java Heap is divided into three generation for sake of garbage collection. These are young generation, tenured or old generation and Perm area.

2) New objects are created into young generation and subsequently moved to old generation.

3) String pool is created in Perm area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM.

4) Minor garbage collection is used to move object from Eden space to Survivor 1 and Survivor 2 space and Major collection is used to move object from young to tenured generation.

5) Whenever Major garbage collection occurs application threads stops during that period which will reduce application’s performance and throughput.

6) There are few performance improvement has been applied in garbage collection in java 6 and we usually use JRE 1.6.20 for running our application.

7) JVM command line options –Xmx and -Xms is used to setup starting and max size for Java Heap. Ideal ratio of this parameter is either 1:1 or 1:1.5 based upon my experience for example you can have either both –Xmx and –Xms as 1GB or –Xms 1.2 GB and 1.8 GB.

8) There is no manual way of doing garbage collection in Java.


10 Points about Java Heap Space


1. Java Heap Memory is part of Memory allocated to JVM by Operating System.

2. Whenever we create objects they are created inside Heap in Java.

3. Java Heap space is divided into three regions or generation for sake of garbage collection called New Generation, Old or tenured Generation or Perm Space.

4. You can increase or change size of Java Heap space by using JVM command line option -Xms, -Xmx and -Xmn. don't forget to add word "M" or "G" after specifying size to indicate Mega or Giga. e.g you can set java heap size to 258MB by executing following command java -Xmx256m HelloWord.

5. You can use either JConsole or Runtime.maxMemory(), Runtime.totalMemory(), Runtime.freeMemory() to query about Heap size programmatic in Java.

6. You can use command "jmap" to take Heap dump in Java and "jhat" to analyze that heap dump.

7. Java Heap space is different than Stack which is used to store call hierarchy and local variables.

8. Java Garbage collector is responsible for reclaiming memory from dead object and returning to Java Heap space.

9. Don’t panic when you get java.lang.outofmemoryerror, sometimes its just matter of increasing heap size but if it’s recurrent then look for memory leak in Java.

10. Use Profiler and Heap dump Analyzer tool to understand Java Heap space and how much memory is allocated to each object.

Difference between soap and restfull webservice java


Both SOAP and RESTful web services allows a client to query server for some information, but the way they are implemented and used is quite different. Main difference between SOAP and REST is that SOAP provides an standard form of communication between client, server and other parties and has restricted set of rules and format, while REST uses to maximum of HTTP protocol, in both client and servers, to allow them to communicate with each other regardless of their implementation.

I found some really awesome comparisons on web, I am posting here


REST vs SOAP Web Services

I am seeing a lot of new web services are implemented using a REST style architecture these days rather than a SOAP one. Let’s step back a second and explain what REST is.

What is a REST Web Service?
The acronym REST stands for Representational State Transfer; this basically means that each unique URL is a representation of some object. You can get the contents of that object using an HTTP GET, to delete it, you then might use a POST, PUT, or DELETE to modify the object (in practice most of the services use a POST for this).

Who's using REST?
All of Yahoo's web services use REST, including Flickr, del.icio.us API uses it, pubsub, bloglines, technorati, and both eBay, and Amazon have web services for both REST and SOAP.

Who's using SOAP?
Google seems to be consistent in implementing their web services to use SOAP, with the exception of Blogger, which uses XML-RPC. You will find SOAP web services in lots of enterprise software as well.

REST vs SOAP
As you may have noticed the companies I mentioned that are using REST api's haven't been around for very long, and their api’s came out this year mostly. So REST is definitely the trendy way to create a web service, if creating web services could ever be trendy (let’s face it you use soap to wash, and you rest when you’re tired). The main advantages of REST web services are:

Lightweight - not a lot of extra xml markup Human Readable Results Easy to build - no toolkits required SOAP also has some advantages:

Easy to consume - sometimes Rigid - type checking, adheres to a contract Development tools For consuming web services, its sometimes a toss up between which is easier. For instance Google's AdWords web service is really hard to consume (in CF anyways), it uses SOAP headers, and a number of other things that make it kind of difficult. On the converse, Amazon's REST web service can sometimes be tricky to parse because it can be highly nested, and the result schema can vary quite a bit based on what you search for.

Note: Whichever architecture you choose make sure it’s easy for developers to access it, and well documented.


Another Reference:

RESTful Services are appropriate in these scenarios:
•          If you have limited bandwidth
•          If your operations are stateless
•          If your clients require caching

While SOAP is the way to go when:
•          If you require asynchronous processing
•          If you need formal contract/Interfaces
•          In your service operations are state full

Traditional Threads vs. Virtual Threads: A Performance Benchmark on Spring Boot 4

Traditional Threads vs. Virtual Threads: A Performance Benchmark on Spring Boot 4 Bottom line: For high-concurrency Spring Boot apps on mo...