Wednesday, February 5, 2020

When to use intern() method of String in Java?

Oracle Java Tutorial and Materials, Oracle Java Certifications, Oracle Java Exam Prep, Java Prep

The String.intern() method can be used to deal with the String duplication problem in Java. By carefully using the intern() means you can save a lot of heap memory consumed by duplicate String objects. A String object is said to be duplicate if it contains the same content as another string but occupied different memory location e.g. str1 != str2 but str1.equals(str2) is true. Since String object consumes a large amount of heap memory in average Java application, it makes sense to use the intern() method to reduce duplication and take advantage of String pool feature provided by Java. You can use intern() method to intern a String object and store them into String pool for further reuse.

For example, when you create a String literal like "ABC" then it's automatically stored in String pool, but when you create a new String object, e.g. new String("abc"), even though it's the same String, a new object at a different memory location is created. This is a duplicate String.

By calling the intern() method on this object, you can instruct JVM to put this String in the pool and whenever someone else creates "abc", this object will be returned instead of creating a new object.

This way, you can save a lot of memory in Java, depending upon how many Strings are duplicated in your program.

Some important things about String.intern() method


Here are some of the important points about the intern() method from java.lang.String class which is worth remembering:

1) The String.intern() method is there in the String class from JDK 1.1. It returns a canonical representation of String object. When the intern method is invoked, if the String pool already contains that String object such that equals() return true, it will return the String object from the pool, otherwise it will add that object to the pool of unique String.

2) After calling intern() method on s1 and s2, s1.intern() == s2.intern(), if s1.equals(s2) because both will be pointing same String constant in pool.

3) Prior to Java 6, uncontrolled usage of String.intern() method can cause java.lang.OutOfMemory: PermGen space because String pool was physically located on PermGen area of Java heap, which is quite small in many JVM (32M to 96M) and fixed.

From Java 7 onward, the intern()  method has become even more useful because the String pool is relocated to the main heap space of JVM.

This will help to further reduce String duplication by using String.intern() method.

In the below diagram you can see that s3 and s4 are referring to the same String object "java" in the String pool because they are interned String while s1 and s2 are referring to separate object because they are not interned or not using String literal.

Oracle Java Tutorial and Materials, Oracle Java Certifications, Oracle Java Exam Prep, Java Prep

4) Another thing to know about is that the intern() method is a non-static method and should be called using a String literal or String object in Java.

That's all about when to use String.intern() method in Java. The Java 8 update 20 also introduced a new feature called String deduplication, which can reduce memory footprint caused by duplicate String without writing a single line of code, but, unfortunately, it's only available for G1 garbage collector and you cannot use it if you are using a ConcurrentMarkSweep garbage collector.

Tuesday, February 4, 2020

How Linear Search or Sequential Search Algorithms works in Java? Example

In that article, someone asked me about is there any other search algorithm exists? How can you search an element in the array if it's not sorted, and you cannot use the binary search algorithm? To answer his questions, I mentioned about the Linear search algorithm, which is the predecessor of binary search. Generally, it is taught before the binary search algorithm because the binary search is faster than Linear search. However, nevermind, you can still learn this useful algorithm to search an item in the array or linked list.

Oracle Java Study Materials, Oracle Java Learning, Oracle Java Guides, Oracle Java Prep

Linear search or sequential search is a method for finding a particular value in a list that consists of checking every one of its elements, one at a time and in sequence until the desired one is found.

The Linear search algorithm is the most straightforward. For a list of n items, the best case is when the value is equal to the first element of the list, in which case only one comparison is needed. The worst case is when the value is not in the list (or occurs only once at the end of the list), in which case n comparisons are needed.

The worst-case performance scenario for a linear search is that it has to loop through the entire collection, either because the item is the last one, or because the item is not found.

In other words, if you have N items in your collection, the worst-case scenario to find a topic is N iterations. In Big O Notation it is O(N). The speed of search grows linearly with the number of items within your collection. Unlike the Binary Search algorithm, Linear searches don't require the collection to be sorted.

Btw, if you are not familiar with the essential data structure and algorithms like this one, it's better to first go through a suitable data structure and algorithm course like Data Structures and Algorithms: Deep Dive Using Java. This is a comprehensive resource to learn fundamental data structures and algorithms in Java programming languages. It's also very affordable, and you can buy in just $10 on Udemy's monthly sale.

Java Program to perform Linear Search


Here is our sample program to implement a sequential search algorithm in Java. It's self-explanatory, but if you have any doubt in understanding any part of the code then please shout and I would be happy to clear any doubt you have.

You can also read the Grokking Algorithms book, one of my favorite books to learn fundamentals Data Structure and Algorithms. It has a whole chapter on the liner and binary search and here is a diagram which neatly explains the difference between linear and binary search algorithm.

Oracle Java Study Materials, Oracle Java Learning, Oracle Java Guides, Oracle Java Prep

You can see how the linear search algorithm because slower and slower as the size of the array or number of elements increases.

import java.util.Arrays;
import java.util.Scanner;

/**
* Java program to implement linear search algorithm in Java. It's also known as
* sequential search, because its sequentially search array for desired element.
* It's best case performance is O(1), when number is located at first index of
* array, in worst case it can take upto N array index access and N comparison.
* In Big O notation, time complexity of linear search is O(n), where n is
* number of elements in array.
*
* @author Javin
*/
public class LinearSearchDemo {

    public static void main(String args[]) {

        int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};

        for (int number : primes) {
            int index = linearSearch(primes, number);
            if (index != -1) {
                System.out.printf("'%d' is found at index '%d' %n", number,
                         index);
            } else {
                System.out.printf("'%d' not found in array %n", number,
                     Arrays.toString(primes));
            }
        }

    }

    /**
     * Search a number in array using linear search algorithm. It's one of the
     * simplest algorithm in programming world, which just require iterating
     * over array and comparing each element with desired one. Once found you
     * break the loop and return index of element.
     *
     * @param array
     * @param number
     * @return index of number in array, or -1 if not found
     */
    public static int linearSearch(int[] array, int number) {
        for (int i = 0; i < array.length; i++) {
            if (array[i] == number) {
                return i;
            }
        }
        return -1; // Number not found in array
    }

}

Output:
'2' is found at index '0'
'3' is found at index '1'
'5' is found at index '2'
'7' is found at index '3'
'11' is found at index '4'
'41' is found at index '12'
'43' is found at index '13'
'47' is found at index '14'

That's all about how to implement a linear search algorithm in Java. It is one of the first search algorithms you should learn in your computer science class. Teachers and Professors explain binary search next, but you have already learned that. Nevermind, we have a lot of sorting algorithms that you can explore after this, and the following article will help you.

Friday, January 31, 2020

What is happens-before in Java Concurrency? An example

Java Concurrency, Oracle Java Tutorial and Material, Oracle Java Study Materials, Oracle Java Prep

A couple of days ago, one of my readers messaged me on LinkedIn about a Java interview question he has recently faced - what is the happens-before relationship in Java concurrency? What is the benefit of it, and how exactly it works? He kind of has some ideas about that its related to the Java Memory Model and provides some sort of visibility guaranteed but couldn't explain with conviction to his interviewer, particularly with a code example and was a bit disappointed. He then asked me if I can write an article about it. I said you should have read the Java concurrency in Practice book before the interview, that would have helped, but nonetheless, I liked the idea to just provide a quick overview of what is the happens-before relationship between threads in Java.

To understand the happens-before relationship, you need to first understand what problems can occur if the same variable is accessed by multiple threads? particularly if one thread writes into the variable, and one thread read from it at the same time.

For example, let's say we have the following code, which is executed by Thread T1, (note, integer variable y is initialized before x)

int y = 1;
int x = 2;

Now, we have another piece of code which is executed by another thread T2 where the value of both the variable is printed (note variable x is printed before y) :

System.out.print(x);
System.out.println(y);

What do you think? What should be printed on the screen? If this code is executed by the same thread, then it's guaranteed that 2 and 1 will be printed, but with multiple threads, there is no guaranteed behavior. It's entirely possible that T2 could not see the assignments made by T1 and just print 0 for both x and y.

It's also possible that it can just see the initialization of either x or y and print accordingly.

This is scary and unpredictable, think what will happen if X is money in your bank account, you definitely want a predictable behavior.

That's where happens-before comes into play. It provides some sort of ordering and visibility guarantee. There is a lot of rule concerning Happens-before (which you can read on Java Concurrency in Practice). Still,  the most important one is if there is a synchronization like a synchronized block or a volatile variable then.

- "A volatile write will happen before another volatile read."
- "An unlock on the synchronized block will happen before another lock."

And, (this is most important)

All the changes which are visible to T1 before a volatile write or a synchronized unlock will be visible to thread T2 after a volatile read of the same variable or locking on the same monitor.

This statement is the most important one, and it can be best understood by the following diagram:

Java Concurrency, Oracle Java Tutorial and Material, Oracle Java Study Materials, Oracle Java Prep
Image credit - Java Concurrency in Practice

You can see that before unlock, thread T1 can see y=1 and x=1, so after T2 gets a lock on the same object, it can also see y=1 and x=1, even though y is not a volatile variable or read inside the lock or synchronized context. This is also true for volatile write and volatile read, which offers slightly less form of synchronization but a great alternative when it comes to visibility.

Now, let's go back to our example if we modify our code like this:

T1:
int y = 1;
volatile int x = 2;

T2:
System.out.print(x);
System.out.println(y)

What do you think? What does the code print now? 2 and 1 or 2 and 0?

Well, if you apply the happens-before than when T1 does a volatile write, and T2 does a volatile read, then it will also see the value of y=1, which is not volatile. Isn't behavior is now more predictable.

The critical thing to remember here is that even the value of a non-volatile variable is visible to thread T2. This is just one example of a happens-before relationship but very useful in analyzing the behavior of a multi-threaded program.

If you are serious about improving your understanding of Java concurrency knowledge and skills, I strongly suggest you should read the Java Concurrency in Practice book by Brian Goetz, Joshua Bloch, Doug Lea and team, one of the best resources for Java developers.

Java Concurrency, Oracle Java Tutorial and Material, Oracle Java Study Materials, Oracle Java Prep

Thursday, January 30, 2020

Difference between SendRedirect() and Forward() in JSP Servlet

Java SendRedirect(), Java Forward(), JSP Servlet, Oracle Java Tutorial and Material

Difference between SendRedirect and forward is one of classical interview questions asked during java web developer interview. This is not just applicable for servlet but also for JSP in which we can use forward action or call sendRedirect() method from scriptlet. Before examining difference on forward and SendRedirect let’s see what send Redirect method and forward method does.

SendRedirect (): 

This method is declared in HttpServletResponse Interface.

Signature: void sendRedirect(String url)

This method is used to redirect client request to some other location for further processing ,the new location is available on different server or different context.our web container handle this and transfer the request using  browser ,and this request is visible in browser as a new request. Some time this is also called as client side redirect.

Forward():

This method is declared in RequestDispatcher Interface.

Signature: forward(ServletRequest request, ServletResponse response)
This method is used to pass the request to another resource for further processing within the same server, another resource could be any servlet, jsp page any kind of file.This process is taken care by web container when we call forward method request is sent to another resource without the client being informed, which resource will handle the request it has been mention on requestDispatcher object which we can get by two ways either using ServletContext or Request. This is also called server side redirect.

RequestDispatcher rd = request.getRequestDispatcher("pathToResource");
  rd.forward(request, response);

Or

RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
  rd.forward(request, response);

Difference between SendRedirect and Forward


Now let’s see some difference between these two method of servlet API in tabular format.

Forward() SendRediret() 
When we use forward method request is transfer to other resource within the same server for further processing. In case of sendRedirect request is transfer to another resource to different domain or different server for futher processing.
In case of forward Web container handle all process internally and client or browser is not involved.  When you use SendRedirect container transfers the request to client or browser so url given inside the sendRedirect method is visible as a new request to the client.
When forward is called on requestdispather object we pass request and response object so our old request object is present on new resource which is going to process our request In case of SendRedirect call old request and response object is lost because it’s treated as new request by the browser.
Visually we are not able to see the forwarded address, its is transparent In address bar we are able to see the new redirected address it’s not transparent.
Using forward () method is faster then send redirect.  
SendRedirect is slower because one extra round trip is required beasue completely new request is created and old request object is lost.Two browser request requird.
When we redirect using forward and we want to use same data in new resource we can use request.setAttribute () as we have request object available. But in sendRedirect if we want to use we have to store the data in session or pass along with the URL.

Example of forward and SendRedirect in JSP Servlet:


Any kind of online payment when we use merchant site will redirect us to net banking site which is completely new request it process our request and again redirect to merchant site?

In Banking Application when we do login normally we use forward method. In case of online banking we are asked for username and password if it’s a correct some another servlet or resource will handle the request other wise request has been forwarded to error page.

Which one is good?


Its depends upon the scenario that which method is more useful.

If you want control is transfer to new server or context and it is treated as completely new task then we go for Send Redirect.
 
Normally forward should be used if the operation can be safely repeated upon a browser reload of the web page will not affect the result.

SendRedirect and forward method are still very useful while programming or working on any web application project using servlet jsp. This is still a popular interview questions so don’t forget to revise forward and sendRedirect before appearing for any job interview.

Wednesday, January 29, 2020

Difference between JRE JVM and JDK in Java Programming language

JRE JVM and JDK, Oracle Study Materials, Oracle Learning, Oracle Guides, Oracle Certification

JRE, JVM, and JDK are three terms you often heard in conjunction with Java programming language and most people either confuse them or think they all are same. In this java article, we will what is Java Run-time (JRE), what is Java virtual Machine (JVM) and what is Java development Kit (JDK) along with Just in Time compiler or JIT. Once you know what JRE, JVM or JDK means you can differentiate them easily by yourself.

JRE JVM and JDK in Java Programming language


Java Runtime Environment (JRE)

Java is every where in browser, in mobile, in TV or in set-top boxes and if you are into Java programming language than you know that Java code which is bundled in JAR (Java archive) file require Java virtual machine JVM to execute it. Now JVM is an executable or program like any other program and you can install that into your machine. You have seen browser often suggesting download JRE to run a Java Applet downloaded from Internet. Various version of JRE are available in java.oracle.com and most of the user who just want to execute Java program inside browser or standalone downloads JRE. All browsers including Internet Explorer, Firefox and Chrome can work with JRE.

Java Virtual Machine (JVM)

When you download JRE and install on your machine you got all the code required to create JVM. Java Virtual Machine is get created when you run a java program using java command e.g. java HelloWorld. JVM is responsible for converting byte code into machine specific code and that's why you have different JVM for Windows, Linux or Solaris but one JAR can run on all this operating system. Java Virtual machine is at heart of Java programming language and provide several feature to Java programmer including Memory Management and Garbage Collection, Security and other system level services. Java Virtual Machine can be customized e.g we can specify starting memory or maximum memory of heap size located inside JVM at the time of JVM creation. If we supplied invalid argument to java command it may refuse to create Java Virtual Machine by saying "failed to create Java virtual machine: invalid argument". In short Java Virtual Machine or JVM is the one who provides Platform independence to Java.

Java Development Kit (JDK)

JDK is also loosely referred as JRE but its lot more than JRE and it provides all the tools and executable require to compile debug and execute Java Program. Just like JRE, JDK is also platform specific and you need to use separate installer for installing JDK on Linux and Windows. Current Version of JDK is 1.7 which is also referred as Java7 and it contains javac (java compiler) based on programming rules of Java7 and Java which can execute java7 code with new features like String in Switch, fork-join framework or Automatic Resource Management. When you install JDK, installation folder is often referred as JAVA_HOME. All binaries are located inside JAVA_HOME/bin which includes javac, java and other binaries and they must be in your system PATH in order to compile and execute Java programs.

JRE JVM and JDK, Oracle Study Materials, Oracle Learning, Oracle Guides, Oracle Certification

Difference between JRE, JDK and JVM


In short here are few differences between JRE, JDK and JVM:

1)  JRE and JDK come as installer while JVM are bundled with them.

2)  JRE only contain environment to execute java program but doesn’t contain other tool for compiling java program.

3)  JVM comes along with both JDK and JRE and created when you execute Java program by giving “java” command.

Just in Time Compiler (JIT)


Initially Java has been accused of poor performance because it’s both compiles and interpret instruction. Since compilation or Java file to class file is independent of execution of Java program do not confuse. Here compilation word is used for byte code to machine instruction translation. JIT are advanced part of Java Virtual machine which optimize byte code to machine instruction conversion part by compiling similar byte codes at same time and thus reducing overall execution time. JIT is part of Java Virtual Machine and also performs several other optimizations such as in-lining function.

That’s all on JRE, JDK and Java Virtual machine and difference between them. Though they look similar they are different and having a clear idea of JVM, JIT or JDK helps in java programming.

Tuesday, January 28, 2020

Introduction to HTTP/2 support in Java 9

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Learning, Oracle Java Certifications

1. Introduction


The IETF streaming group approved the HTTP/2 protocol in 2015, sixteen years after HTTP/1.1 had been released. HTTP/2 comes with the promise of lowering latency and makes many of those workarounds obsolete which were necessary for HTTP/1.1 in order to be able to keep up with today’s response time requirements. In this article, I introduce HTTP/2 briefly and how it renews the text-based HTTP/1.1 and then we look into the upcoming HTTP/2 support in Java 9.

2. Latency optimization techniques for HTTP/1.1


People are getting more and more inpatient on the Internet, but they wouldn’t notice that the actions they’re performing on the web aren’t being performed by themselves directly, if response time if below 100ms.

When response time goes up to 1sec that does get noticed and when it takes longer than 10s for a site to respond, it’s considered to be out of order. According to some research the average attention span has decreased to 7-8 seconds and even a 1sec delay could cause 7% loss in revenue.

HTTP/1.1 has needed (sometimes heavy) workarounds to meet today’s requirements.
  • As one HTTP connection can download one resource at a time, browsers fetch them concurrently in order to be able to render the page faster. However, the number of parallel connections per domain is limited and domain sharding was used to work that around.
  • A similar optimization technique was to combine multiple resources (CSS, JavaScript) into a single bundle in order to be able to get them with a single request. The trade-off is sparing a network round-trip with the risk of not using some parts of the assembled resource bundle at all. In some cases complicated server side logic takes care of selecting the pertinent static resources and merging them for particular page request
  • Image sprites is a technique similar to bundling CSS and JavaScript files for lowering the number of requests.
  • Another technique being is in-lining static resources to the HTML


3. A brief introduction to HTTP/2



HTTP/2 is meant to alleviate the pain stemming from maintaining complex infrastructures for HTTP/1.1 in order to make it perform well. Although HTTP/2 is still backward compatible with HTTP/1.1, it’s not a text based protocol any more. Clients establish a connection as an HTTP/1.1 request and requests and upgrade. From that on, HTTP/2 talks in binary data frames.

3.1. HTTP/2 multiplexing

HTTP/2 multiplexing makes all of the HTTP/1.1 workarounds above obsolete, because a single connection can handle multiple bi-directional streams, thus allowing clients for downloading multiple resources over a single connection simultaneously.

3.2. HTTP/2 header compression

The HTTP 1.x protocols were text-based and thus they were verbose. Sometime the same set of HTTP headers were exchanged all over and over again. HTTP/2 diminishes the required bandwidth drastically by maintaining a HTTP header table across requests. Essentially this is de-duplication and not compression in the classical sense.

3.3. HTTP/2 push

You might think that HTTP/2 push is the continuation or an upgrade of some kind to WebSocket, but it’s not the case. While WebSocket is a means to full-duplex communication between the client and the server in order to allow the server to send data to clients once a TCP connection has been established, HTTP/2 solves a problem separate to that.

HTTP/2 push is about sending resources to clients proactively without having to ask for it from the client’s perspective. This practically means that the server side knows that a website needs some images and it sends them all at once (ahead of time) long before clients requests them.

4. Java HTTP clients supporting HTTP/2


According to one of the Wiki pages of the HTTP/2, at the time of writing the following Java client libraries are available for establishing HTTP/2 connections.

◉ Jetty

◉ Netty

◉ OkHttp

◉ Vert.x

◉ Firefly

In this article however, we’re focusing on the HTTP/2 support provided by Java 9. JEP 110 specifies the requirements and it also states that the project is still in incubation state, which practically means that it’s not going to replace the existing UrlConnection API in java 9.

Only with Java 10 will the standard Java HTTP/2 client be moved under package java.net. In the meantime however, it will live underneath the jdk.incubtor namespace.

5. Explore HTTP/2 Client of Java 9


JEP 110 sets requirements for the new, built-in HTTP/2 client so that it provide a high-level, easy to use API and comparable (or higher) performance than existing alternatives (see above).

The first step is import module jdk.incubator.httpclient.

module com.springui.echo.client {
  requires jdk.incubator.httpclient;
}

For the sake of this example, we’ll be using Undertow as a HTTP/2 compliant web server. It just echoes back that message what clients send to it.

public class EchoServer {

  private static final Logger LOGGER = Logger.getLogger(EchoServer.class.getSimpleName());

  private static final int PORT = 8888;
  private static final String HOST = "localhost";

  public static void main(final String[] args) {
    Undertow server = Undertow.builder()
        .setServerOption(UndertowOptions.ENABLE_HTTP2, true)
        .addHttpListener(PORT, HOST)
        .setHandler(exchange -> {
          LOGGER.info("Client address is: " + exchange.getConnection().getPeerAddress().toString());
          exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
          exchange.getRequestReceiver().receiveFullString((e, m) -> e.getResponseSender().send(m));
        }).build();

    server.start();
  }

}

The new API follows the builder pattern everywhere and HttpClient, which is the entry point of initiating HTTP requests, is no exception to that.

HttpClient client = HttpClient
    .newBuilder()
    .version(Version.HTTP_2)
    .build();

5.1. Sending a request in blocking mode

Once we have an HttpClient instance, HttpRequest instances can also be constructed with a builder.

HttpResponse<String> response = client.send(
    HttpRequest
        .newBuilder(TEST_URI)
        .POST(BodyProcessor.fromString("Hello world"))
        .build(),
    BodyHandler.asString()
);

Method send block as long as the request is being processed, however there’s a way to exchange HTTP messages asynchronously as well.

5.2. Sending requests in non-blocking mode

In the following example 10 random integers get sent to our HTTP echo server asynchronously and when all of the requests have been initiated, the main thread waits for them to be completed.

List<CompletableFuture<String>> responseFutures = new Random()
    .ints(10)
    .mapToObj(String::valueOf)
    .map(message -> client
        .sendAsync(
          HttpRequest.newBuilder(TEST_URI)
            .POST(BodyProcessor.fromString(message))
            .build(),
          BodyHandler.asString()
        )
        .thenApply(r -> r.body())
    )
    .collect(Collectors.toList());

CompletableFuture.allOf(responseFutures.toArray(new CompletableFuture<?>[0])).join();

responseFutures.stream().forEach(future -> {
  LOGGER.info("Async response: " + future.getNow(null));
});

5.3. Processing push-promise frames

All of the examples above could have been normal, old fashioned HTTP/1.1 requests. Apart from creating the HttpClient, nothing HTTP/2 specific can be observed.

Probably the most relevant HTTP/2 feature of the client API is the way it handles multiple responses when HTTP/2 push is used.

Map<HttpRequest, CompletableFuture<HttpResponse<String>>> responses =
  client.sendAsync(
    HttpRequest.newBuilder(TEST_URI)
      .POST(BodyProcessor.fromString(TEST_MESSAGE))
      .build(),
    MultiProcessor.asMap(request -> Optional.of(BodyHandler.asString()))
  ).join();
responses.forEach((request, responseFuture) -> {
  LOGGER.info("Async response: " + responseFuture.getNow(null));
});


Source: javacodegeeks.com