Java-Success Blog

Apr 29, 2014

When to use Java 8 functional programming, and where does it shine?

Q. What is the difference between imperative and declarative programming paradigms?A. Imperative (or procedural) programming: is about defining the computation how to do something in terms of statements and state changes, and as a result what you want to happen will happen.

Declarative programming: is about declaratively telling what you would like to happen, and let the library or functions figure out how to do it. SQL, XSLT and regular expressions are declarative languages.

Q. Does functional programming use imperative or declarative approach?A. Functional programming is a form of declarative programming, where functions are composed of other functions -- g(f(x)) where g and f are functions. An output of one function becomes the input for the composing function. A typical example of functional programming, which you may have used is transforming an XML document using XSLT to other forms. The composable and isolated XSL style sheets are used for transformation.

In imperative programming it makes sense to say x = x + 1, but in maths or functional programming it is not right to say x = x + 1, if x is 2 is it right to say 2 = 2 + 1 or 2 = 3 ?In functional programming f(x) -> x + 1, where f is a function that takes an argument of x.

Q. What does functional programming shine in Java 8?A.

Scenario 1: Here is an imperative program to extract odd numbers from a given list of numbers and then double each odd number and print each of them.

Shining moment 1: The above code has increased readability and maintainability because each function is designed to accomplish a specific task for given arguments. Lesser moving parts than the imperative code. The above code can be further improved by extracting the cryptic lambda expressions like (e) -> (e * 2) to static methods with meaningful names for re-usability and readability as shown below.

Shining moment 2: A time delay was added on purpose to demonstrate that a functional program can be easily made to run in parallel using the "fork and join" feature added in Java 7. To improve performance of the above code that took 9.5 seconds to run, all you have to do is use .parallelStream( ) instead of .stream( ).

Finished running in 3 seconds with the performance gain. When parallelising tasks, you need to be

Ensuring that the computation is correct

Ensuring that parallelism actually brings performance gains

Using algorithms that are parallelisable

Shining moment 3: code is easier to refactor as shown below. If you want to switch the logic to double it first and then extract the odd numbers, all you have to do is swap the .filter call with .map call.

Shining moment 4: Easier testing and debugging. Because pure functions can more easily be tested in isolation, you can write test code that calls the pure function with typical values, valid edge cases, and invalid edge cases. In the above example, I was using the Java 8 library that was well tested with confidence. I will only have to provide unit tests for the static functions boolean isOddNumber(int number) and int doubleIt(int number) that provide the logic.

Core Java coding question on palindrome

Q. What is a palindrome?A. A palindrome is a word or sentence that reads the same forward as it does backward. For example, the terms "racecar", "dad", "madam" and the name "Hannah". The longest palindromic substring of "bananas" is "anana" -- the left side of a palindrome is a mirror image of its right side.

Q. How will you find the longest palindrome of a given string?A. Algorithm: Have 2 center pointers, and move one to the left and the other to the right. Cater for 2 scenarios where you have odd number of characters and even number of characters as shown below.

BODMAS, tells us to attend to Brackets, Of, Division, Multiplication, Addition, and Subtraction

This means:

(1+2)*3 = 9 using BODMAS or "Please Excuse My Dear Aunt Sally"

Polish Notation was invented in the 1920's by Polish mathematician Jan Lukasiewicz, who showed that by writing operators in front of their operands, instead of between them, brackets were made unnecessary.

3 2 1 + x = 9 using Reverse Polish Notion (RPN).

In programming, the RPN is evaluated using a stack, which is a LIFO (Last In First Out) data structure.

The algorithm for RPN is:

Keep pushing the numbers into a stack, and when it is an operator, pop two numbers from the stack, do the calculation, and push back the result.

Q. Can you write code that demonstrates RPN?A. It can be coded in Java 7, as shown below. Java 7 supports string in switch statements.

Apr 26, 2014

The part-1 and part-2 built the simpleWeb war file outside eclipse using Maven. In this post, let's cover how eclipse interacts with Maven.

Step 1: start up your eclipse and verify if it has m2e (Maven to Eclipse) plugin. Click on Help --> About Eclipse

Step 2: Eclipse needs to know where your Maven settings.xml file is so that it can access your local repository. Click on Window --> Preferences --> Maven --> User Settings.

Step 3: You can import any Maven artifact into eclipse. That is with a pom.xml file. Click on File --> Import, and select "Existing Maven Projects" from within Maven.

Step 4: Browse and select your simpleWeb project.

Step 5: You can now work within eclipse.

Step 6: Go to your DOS command prompt, and then run mvn eclipse:eclipse from the simpleWeb folder.

Step 7: Now come back to eclipse and select simpleWeb and press F5 to refresh the project. You should now see the referenced libraries read from your pom.xml file.

Step 8: You can now run within eclipse by right-clicking on simpleWeb and then selecting RunAs and then Maven clean, Maven install, Maven test, etc. Alternatively, select "Maven build" and eneter a goal to execute like "package".

Apr 22, 2014

Understanding Java generics with the help of scenarios and working examples -- part 1

Q1. If java.lang.Object is the super type for java.lang.Number and, Number is the super type for java.lang.Integer, am I correct in saying that List<Object> is the super type for List<number> and, List<Number> is the super type for List<Integer>.

A1. No. List<Object>is not the the super type of List<Number>. If that were the case, then you could add objects of any type, and it defeats the purpose of Generics.

In Generics, wildcards (i.e. ?), makes it possible to work with super classes and sub classes.Q2. How will you go about deciding which of the following to use?

<Number>

<? extends Number>

<? super Number>

A2. Here is the guide:

1. Use the ? extends wildcard if you need to retrieve object from a data structure. That is read only. You can't add elements to the collection.2. Use the ? super wildcard if you need to put objects in a data structure.3. If you need to do both things (read and add elements), don’t use any wildcard.

Apr 15, 2014

Understanding dynamic proxies in Java with a practical example -- Service retry example

Design pattern: If you are asked to describe or talk about a design pattern, you could mention this dynamic proxy class as a proxy design pattern. Many pick either singleton or factory design pattern. It would be nicer to pick something other than these two common patterns. Some interviewers specifically ask you to pick anything except factory and singleton design pattern.

In real life applications, you need to retry services that fail. Let's us this retry service scenario to demonstrate dynamic proxy design pattern in Java.

Step 1: Create a dummy service to emulate an internal or external service with outage.

public interface DummyService {
abstract void execute();
}

Step 2: The dummy service implementation that emulates failure every time except every 3rd call.

Apr 14, 2014

Understanding Big O notations through Java examples

Q. Have you seen job advertisements requiring Java candidates to work in real-time or high volume transaction processing systems?

If you are applying for such jobs, you can be quizzed on Big O notation. Here are some basics to brush up on.

Big-O gives you the upper bound. For example, if you need to search an element in an array and you expect the array to be large, you might just say that you opt for a binary search instead of a sequential scan because the former has O(log n) complexity wheres the latter has O(n) complexity.

Big-O

Description/Example

If n=10, and c=2

If n=20, and c=2

O(1)
Constant

Running time is constant.

Determining if a String is equal to a given value

if(str.equals("java"))
{
return true;
}
else {
return false;
}

A Map look up by key -- map.get(key);

1

1

O(log n)

Logarithmic

Running time increases logarithmically in proportion to the input size.

Finding an item in a sorted array with a binary search

For example, search for 2 in a list of numbers 1,2,3,4,5,6,7

Step 1: Sort the data set in ascending order as binary search works on sorted data.

Step 2: Get the middle element (e.g. 4) of the data set and compare it against the search item (e.g. 2), and if it is equal return that element

Step 3: If search item value is lower, discard the second half of the data set and use the first half (e.g. 1,2,3). If the search item value is higher, then discard the first half and use the second half (e.g. 5,6,7)

Step 4: Repeat steps 2 and 3 until the search item is found or the last element is reached and search item is not found.

Those who worked with Java IO may still remember the headaches that framework caused. It was never easy to work seamlessly across operating systems or multi-file systems. The NIO 2.0 has come forward with many enhancements. It’s also introduced new classes to ease the life of a developer when working with multiple file systems with classes and interfaces such as Path, Paths, FileSystem, FileSystems and others.

Another very handy feature is the WatchService for file change notifications. It can monitor a directory for changes as demonstrated below.

Java 7 has incorporated the feature that would distribute the work across multiple cores and then join them to return the result set as a Fork and Join framework. he effective use of parallel cores in a Java program has always been a challenge. It’s a divide-and-conquer algorithm where Fork-Join breaks the task at hand into mini-tasks until the mini-task is simple enough that it can be solved without further breakups. One important concept to note in this framework is that ideally no worker thread is idle. They implement a work-stealing algorithm in that idle workers “steal” the work from those workers who are busy.

The example below demonstrates this with a simple task of summing up 10 numbers. If the count of numbers to be added are greater than 5, it is forked into chunks of 5 to be processed by separate thread, and the forked sum are then joined to give the overall total of 10 numbers from 1 to 10, which is 55. The total of numbers 1 to 5 is 15, and 6 to 10 is 40.

public class Java7Feature3 {
public static void main(String[] args) {
//pre Java 7
int million = 1000000;
System.out.println(million);
//Java 7. More readable
million = 1_000_000;
System.out.println(million);
//consecutive underscores are allowed
int ten_million = 10__000_000;
System.out.println(ten_million);
//underscores can be used in other numeric types
double million_dollars_5_cents = 1_000_000.0_5d;
System.out.println(million_dollars_5_cents);
//illegal to have underscores
//1. start or end a literal with an underscore _10.00, 10.00_
//2. have underscores before or after a decimal point 10_.00, 10._00
}
}

Output:

1000000
1000000
10000000
1000000.05

#4: AutoCloseable interface.

Java 5 introduced the Closeable interface and Java 7 has introduced the AutoCloseable interface to avoid the unsightly try/catch/finally(within finally try/catch) blocks to close a resource. It also prevents potential resource leaks due to not properly closing a resource. The java.io.InputStream and java.io.OutputStream now implements the AutoCloseable interface.

try can now have multiple statements in the parenthesis and each statement should create an object which implements the new java.lang.AutoCloseable interface. The AutoCloseable interface consists of just one method.
void close () throws Exception {}. Each AutoClosable resource created in the try statement will be automatically closed! If an exception is thrown in the try block and another Exception is thrown while closing the resource, the first Exception is the one eventually thrown to the caller.

Think of the close( ) method as implicitly being called as the last line in the try block.

Apr 9, 2014

Understanding Java 8 Streams and working with collections using Lambda expressions

A stream is an infinite sequence of consumable elements (i.e a data structure) for the consumption of an operation or iteration. Any Collection can be exposed as a stream. The operations you perform on a stream can either be

The above example creates a new list of full time employees. The operations .stream( ), .filter( ) create the intermediate streams, hence they are chained, and the .collect is the terminal operation that returns the final List of full-time employees.

This is enabled in the Iterable interface, which is a functional interface with the forEach default method. A List and other collections implements the Iterable functional interface to allow lambda expressions.

Example 5: The free variables in lambda expressions are not thread-safe.
A lambda expression has 3 aspects:

Parameters

A block of code or body

Values for the free variables. These are the variables that are not parameters, and not defined inside the closure.

The anonymous inner classes can only access variables defined outside if they are marked final. Otherwise you will get a compile error. The lambda expression has relaxed the requirement of variables being final, but the "free variables" that you use need to be either final or effectively final.

The above code gives compile error due to Line A. If you comment out Line A, the above code will compile, and Line B and Line C are ok as they use the variable counterLocal as read only and it is effectively final.

So, mutating free variables in a lambda expression is not thread-safe. The prohibition against mutation only holds true for local variables as explained above. You can still use an instance or static variable, but the compiler won't warn you, but you can have thread-safety issues.

So, there is nothing special about using the "This" keyword in lambda expressions. The scope of lambda expression is nested inside the execute( ) method, and this has the same meaning anywhere inside the execute method.

Apr 4, 2014

Example 3: It is very common to loop through a collection of objects and perform certain tasks like setting a variable, etc. The Iterable from which the other interfaces like Collection, List, etc has been annotated with @FunctionalInterface.

As shown in the diagram, the Iterable also has a default method forEach(Consumer action) implemented to loop through the collection.

The function interfaces and Lambda expressions are going to make your code concise when coding with Java 8. These are the most awaited features among Java developers. If you understand these 2 examples, you will find the other parts easier to understand.

Q. What is a Lambda expression?A. Lambda expressions are anonymous methods which are intended to replace the bulkiness of anonymous inner classes with a much more compact mechanism. Q. What is a functional interface?A. The annotation @FunctionalInterface is being introduced. This annotation acts similarly to @Override by signaling to the compiler that the interface is intended to be a functional interface. The compiler will then throw an error if the interface has multiple abstract methods.

Step 2: Define the SumTest class and provide the Lambda expression to sum 2 numbers. You can think of it as method implementation of sum(int input1, int input2) defined in the functional interface above.

#5 Parallel processing. In pre Java 8, the call to Arrays.sort( ) uses the merge sort algorithm sequentially. Java 8, introduces a new API for sorting the array in parallel with Arrays.parallelSort( ). Arrays.parallelSort( ) uses Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads available in the thread pool. Fork/Join implements a work stealing algorithm where an idle thread can steal tasks queued up in another thread.

#6 The java.util.concurrent.atomic package has been expanded to include four new classes that allow for concurrent, scalable, and updatable variables. LongAccumulator, LongAdder, DoubleAccumulator and DoubleAdder can be used to sum a value across multiple threads, and is generally preferable to the AtomicLong class since it’s considerably faster.

Note: Prior to Java 8, the Java HotSpot VM had a memory space known as PermGen space for storing class metadata. This often lead to java.lang.OutOfMemoryError due to susing up all the PermGen space. In Java 8, the HotSpot VM will no longer have PermGen space, and will instead allocate native memory, called Metaspace to store class metadata, which is similar to the way the JRockit and IBM JVMs operate.