Tuesday, June 2, 2015

Lambda Java 8 - Basic and concise introduction

Introduction

Lambda is a new feature added in Java 8. It is an elegant replacement for anonymous classes which implement functional interfaces (interfaces with single method).

For instance, runnable interface has a single method, run().

With anonymous class, a simple implementation, would look like this,
Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        // Your complex logic goes here ..
        System.out.println("Hello World !!");
    }
});
thread.run();

With Lambda, it would look like the below,
Thread thread = new Thread(() -> {
    // Your complex logic goes here ..
    System.out.println("Hello World !!");
});
thread.run();
Can you see the reduced code and increased code clarity. Lambda improves readability. And for understanding performance of lambda, you can read this,
http://wiki.jvmlangsummit.com/images/7/7b/Goetz-jvmls-lambda.pdf

You may wonder, why do we need a concept which just simplifies anonymous classes with single method. For that we need to understand what is the need for single method interface. Generally single method or functional interface is used where the functionality or implementation to be passed as a method argument. In runnable interface, we pass the code to be run by a new thread. In Java core framework, there are a lot of functional interfaces, like Callable, Comparator, etc. If you carefully at those, implementations of these interfaces, are just to pass the code to other methods.

Syntax of Lambda Expression

Comma separated list of parameters, with enclosing paranthesis and parameters don't need data types as it can be inferred; Followed by single arrow, ->

Body with an expression or a block of statements. In case of expression, runtime would evaluate and return the result. in case of statement block, block has to be properly enclosed by curly braces and return statement has to be added, if needed.

For instance, if x and y are parameters to be passed, a simple lambda expression, might look like this,
(x, y) -> {
// Add needed code here.
return x + y;
}

Capturing variable in the enclosed scope

Lambda expressions can capture variables in the enclosing scope without any problems associated with scoping or shadowing. Variables can't be defined in the lambda body scope with a name, if the same variable name has already been used in the enclosing scope. In the following code snippet, lambda uses the variable, name defined in the enclosing scope,
String name = "Karthik";
Thread thread = new Thread(() -> {
    // Your complex logic goes here ..
    System.out.println("Hello " + name + " !!");
});
thread.run();
Hope this post gave some basic ideas on Lambda,

For more information, please refer,

https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

Friday, May 22, 2015

Spring boot - Quickly bootstrap your web-service or web-app.

Now a days, for quick web-services and web-app implementations, I have started using Spring boot, Just I wanted to share my experiences; in this post, I am just covering the basics of Spring boot framework.

Essentially, Spring boot helps you to,

  • Get rid of manual Spring configurations and absolutely the XML files for configuration. This is a great boost for first timers. :)
  • Create a stand-alone or uber jars and instantly run that on production boxes, with the help of embedded servlet containers like Jetty, Tomcat, etc. Of course, users could opt for container of their choice. Default is Embedded Tomcat. This is again a great boost as configuring embedded containers generally a bit tedious and time consuming.
  • get simplified Maven configurations, with the set of Starter POMs, Spring-boot website says, it is opinionated, but in my view, it is great as this is created by experts in the field and must have been tested fully for optimal dependencies. 
  • make your app or service, production ready (with just adding dependency for Spring actuator) by providing various end-points for health-check, metrics, etc. This is awesome as it makes all your services look uniform when it comes to managing. This reminds me DRY (Don't repeat yourself) for API design :)
  • Simplify spring annotations, like "SpringBootApplication" annotation, which effectively covers essential annotations like Configuration, ComponentScan, etc.
Lets get our hands dirt, to experience Spring boot. 

Create a simple Maven project with your IDE and change your pom, like given below,


This POM is enough for our RESTful service, :) Now can you see how spring boot helps to minimize the maven configurations to the core minimum. 

As you see, POM sets that spring-boot-starter-parent as the parent pom for the project, this is essential part of Spring boot project as it has all the essential core components for the standalone spring based web-service. And in dependencies section, the needed dependencies shall be added, we added the artifact, spring-boot-starter-web. Real power of spring boot lies in this, as it would auto-configure the project as per the dependencies. With spring-boot-starter-web, needed web mvc configurations will be added up automagically :) If you want to have Velocity template engine for your View, you could simply add up the dependency,  spring-boot-starter-velocity, which would make boot to add the essential configurations for Velocity engine. Cool, right ?

To get the service to complete, you may want to add the controller, like given below,



Code is pretty self evident, it handles the end-point, /hello, with simple response, "Hello!".

The main file should be placed under the right package, in our example, this file has to be placed in the package, in.blogspot.karthikpresumes



The annotation, SpringBootApplication is very important, it is an annotation which simply covers all the essential annotations, like Configuration, ComponentScan, etc.

The entire project is hosted here, https://github.com/karthikmit/SpringBootBlog.git

Main reference:

http://projects.spring.io/spring-boot/

Thanks for reading!