New features comes with Java 13

 

JEP 353 — Reimplement the Legacy Socket API

JEP 353 covers the new implementation of the Socket API. To be more precise, an additional, more modern implementation of the Socket API (which was introduced in Java 1), has been added to the core libraries. The old Socket API is available via a JDK system property and the PlainSocketImpl class (but not for long).

The first, and in my opinion most important feature of the new implementation, is that sockets are polled in non-blocking mode and are accessed via an operation limited by a timeout by default. Why is this important? Effectively, it means you can perform operations on a Socket object without having to wait for the Socket to respond before making an additional operation on said Socket. Consider an application that relies on external APIs for a subset of its functionality. If you start the application with a blocking Socket, you will have to wait for your Socket operations to complete before continuing your application. But if you were to initiate a connection to an API service using a non-blocking socket and store the result in a Future<> object, you can continue your application’s initialization steps without waiting for a response. This is particularly convenient when decoupling your application’s initialization and third-party dependencies.

JEP 350 — Dynamic CDS Archives

This particular enhancement modifies the JRE more than anything; most Java developers will not notice this enhancement in their day to day development. The origins of this JEP start in Java 10, with JEP 310. Class-Data Sharing has been around since JDK 5, but it was codified as “Application Class-Data Sharing” for Java 10. Effectively what happens is meta-data across a developer-specified list of classes are shared in an archive file. This archive file is then loaded and referenced by the JVM. If this archive file is built from 100 class files, you save the JVM a lot of time and energy by referencing just the one file. This reduces memory footprint and application load times.

So what feature has been added to CDS in Java 13? Java 13 introduces dynamic archiving. Before Java 13, making a CDS archive required the completion of several steps. As outlined in JEP 350, the steps are:

  1. Do one or more trial runs to create a class list
  2. Dump an archive using the created class list
  3. Run with the archive
    These steps are all achievable via java CLI options. Depending on the size of the application, these commands may be difficult to run. This is where Dynamic CDS comes in. This enhancement performs step 1 at the end of your application’s execution, let’s say in your QA build process. From here its just a matter of building your archive file and dropping it into a CI/CD pipeline for deployment. The manual steps required to build the class list required to create the archive is completely gone with Dynamic CDS Archives.

JEP 351 — ZGC: Uncommit Unused Memory

ZGC was a new garbage collector introduced to Java in Java 11. It was designed to work on environments with massive compute capacity and memory requirements, significantly greater than desktop computing. While other garbage collectors have their perks, ZGC is the best choice for applications with significant memory and compute requirements.

ZGC is not without limits though. Before Java 13, ZGC never returned memory to the OS without a restart. This feature is common to most garbage collectors; most traditional GCs return memory to the OS by default as they were designed to run on commodity or even embedded hardware with severely restricted memory and compute requirements. Not being able to return memory to the OS would have significant repercussions on application performance. If we consider the origins of ZGC though, it is easy to see why this feature was not built-in. If you have thousands of gigabytes of RAM installed on your host machine, you likely do not need to return it to the OS. Regardless, this feature was added to ZGC in Java 13, making it an option for applications that do not always run on specialized, enterprise-level machines.

Future Directions

Java 13 is the next chapter in the quest to make Java a viable functional language. Since Oracle has taken over the development of Java, it has gradually evolved into a modern language, capable of keeping up with the hottest trends in application development. Since Java 8, the language has steadily evolved into a discrete, easily readable, easily extensible language capable of keeping up with other languages like Python, Scala, and Kotlin.

At the time of this post’s writing, Java 14 is scheduled to be released in March of 2020. JEP 352 is the only addition scheduled for Java 14, but that last will likely grow to include several more JEPs from the index before the end of 2019.

 

Related blog:

Spring boot interview questions and answers

devops training in chennai

Java FileHandling Methodology

 

JDK Versions

Java code samples don’t live in isolation, especially when it comes to Java I/O, as the API keeps evolving. All code for this article has been tested on:

  • Java SE 7 (jdk1.7.0_80)
  • Java SE 8 (jdk1.8.0_162)
  • Java SE 9 (jdk-9.0.4)

When there is an incompatibility, it will be stated in that section. Otherwise, the code works unaltered for different Java versions. The main incompatibility is the use of lambda expressions which was introduced in Java 8.

Java File Reading Libraries

There are multiple ways of reading from files in Java. This article aims to be a comprehensive collection of all the different methods.

Closing File Resources

Prior to JDK7, when opening a file in Java, all file resources would need to be manually closed using a try-catch-finally block. JDK7 introduced the try-with-resources statement, which simplifies the process of closing streams. You no longer need to write explicit code to close streams because the JVM will automatically close the stream for you, whether an exception occurred or not. All examples used in this article use the try-with-resources statement for importing, loading, parsing and closing files.

File Location

All examples will read test files from C:\temp.

Encoding

Character encoding is not explicitly saved with text files so Java makes assumptions about the encoding when reading files. Usually, the assumption is correct but sometimes you want to be explicit when instructing your programs to read from files. When encoding isn’t correct, you’ll see funny characters appear when reading files.

All examples for reading text files use two encoding variations:
Default system encoding where no encoding is specified and explicitly setting the encoding to UTF-8.

Code Quality and Code Encapsulation

There is a difference between writing code for your personal or work project and writing code to explain and teach concepts.

If I was writing this code for my own project, I would use proper object-oriented principles like encapsulation, abstraction, polymorphism, etc. But I wanted to make each example stand alone and easily understood, which meant that some of the code has been copied from one example to the next. I did this on purpose because I didn’t want the reader to have to figure out all the encapsulation and object structures I so cleverly created. That would take away from the examples.

For the same reason, I chose NOT to write these example with a unit testing framework like JUnit or TestNG because that’s not the purpose of this article. That would add another library for the reader to understand that has nothing to do with reading files in Java. That’s why all the example are written inline inside the main method, without extra methods or classes.

My main purpose is to make the examples as easy to understand as possible and I believe that having extra unit testing and encapsulation code will not help with this. That doesn’t mean that’s how I would encourage you to write your own personal code. It’s just the way I chose to write the examples in this article to make them easier to understand.

Exception Handling

All examples declare any checked exceptions in the throwing method declaration.

The purpose of this article is to show all the different ways to read from files in Java — it’s not meant to show how to handle exceptions, which will be very specific to your situation.

So instead of creating unhelpful try catch blocks that just print exception stack traces and clutter up the code, all example will declare any checked exception in the calling method. This will make the code cleaner and easier to understand without sacrificing any functionality.

 

Related blog:

Spring boot interview questions

How to enable Junit with Spring boot Projects


 

In this article, we will learn how to enable JUnit 5 in a newly created Spring
Boot project. We are going through the following steps:

  1. Initialize new Sprint Boot project
  2. Having a look at our pom.xml and mostly on sprint-boot-starter-test dependency, going a little deeper in spring-boot-starter-test and see what JUnit version it uses
  3. How to exclude child dependency that comes from one of our dependencies using Maven
  4. Add JUnit 5
  5. Migrate JUnit 4 to JUnit 5

1) First, let’s go to Spring Boot initialize and generate a new project.

The defaults should be fine and you can click the “Generate Project” button. You should have downloaded a .zip archive of the starter Sprint Boot project. Unzip it and open it with IDE of your choice (I am using IntelliJ and the following code samples and examples will be shown from it). After opening it, you should see the following structure:

2) Now let’s focus on the pom.xml.

In our pom.xml we can see the following dependency which includes libraries (such as JUnit, Hamcrest, and Mockito) for testing Spring Boot applications.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
 

We are going a little deeper to see the exact dependencies and their versions focusing on junit with which spring-boot-starter-test comes (in IntelliJ you can do this by Ctrl + click onto spring-boot-starter-test. In the snippet below, we can see that sprint-boot-starter-test comes with JUnit 4.12 but there is JUnit 5 already. So how can we use the newer version of JUnit in our new Spring Boot project?

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
 

3) We should have a way to exclude JUnit 4 because we are currently depending on it because of spring-boot-starter-test. We can do this by adding the following lines to our spring-boot-starter-test dependency by which we exclude JUnit 4.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
  <exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
 

4) We are now going to configure JUnit 5 as a dependency using Maven. We will add the following dependencies in pom.xml

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.3.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.3.2</version>
<scope>test</scope>
</dependency>
 

And we should add the following maven plugin to our build plugins

<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
</plugin>
 

5) We have removed the dependency of JUnit 4, we have added JUnit 5 and now it is time to make a little code changes in order to use JUnit 5. Let’s focus on DemoApplicationTests.java where we can see the following code

package com.example.demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
    @Test
public void contextLoads() {
}
}
 

Actually, the only things that we have to change are the RunWith annotation because it’s from JUnit 4 and the import of Test annotation. After the change, our test should look like

package com.example.demo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class DemoApplicationTests {
    @Test
public void contextLoads() {
}
}

Related blog:

 

Spring boot interview questions

JSP Life cycle Events explained

JSPs are actually servlets, as you have already seen. Container will convert all jsp files into servlets before executing them. JSPs just provide an easy way to create components containing non-java code.

Once a JSP page is created and deployed, container will do some life cycle events, which also includes calling some of its methods similar to servlet life cycle events.

 

Summary of lifecycle events

  1. JSP page translation (validation, translation, compilation phases)

  2. Load Class

  3. Instantiate

  4. jspInit method is called

  5. _jspService method is called

  6. jspDestroy method is called

 

JSP page translation (validation, translation, compilation phases)

  1. Validation is performed before translation. Syntax checking happens and all references to tag libraries, actions and EL functions in the JSP are validated to ensure that they exist and are accessible to the page, and if there are any issues an error occurs and prevents the translation process from continuing.

    • Before validation, JSP page is converted to an XML view and this xml is view is then validated and translated.

  2. Initial JSP input page is translated into servlet source code. While doing so, it will write the print statements for each of your non java lines in the JSP (please see previous demo). This generated servlet should implement HttpJspPage or its parent JspPage based on if the environment is HTTP based or not.

    • A vendor will typically have a specialized JSP base servlet, extending and implementing all required classes or interfaces. In Tomcat, this is called org.apache.jasper.runtime.HttpJspBase. HttpJspBase extends HttpServlet and GenericServlet, and implements HttpJspPage, JspPage, Serializable, Servlet, ServletConfig (please see previous demo).

  3. Servlet source code is then compiled into a servlet class file.

  4. Outputs

    • There are two outputs within the translation phase.

      • The first is an interim output: a Java source file for a servlet.

      • The second is the compiled class file from the servlet source.

    • The class file is retained for future use, and most JSP containers may retain or give you an option whereby you can retain the servlet source for debugging purposes.

    • In Tomcat, the generated servlet Java source and compiled class during JSP translation will, by default, be kept in which directory <Tomcat-Installation-Directory>/work/Catalina/localhost/<context- directory>/org/apache/jsp.

  5. Timing

    • Even though a JSP container has discretion regarding when the translation occurs, by default (in most cases) the JSP is compiled into a servlet and then loaded the first time it is accessed.

    • This might cause a small delay for the first request, but there won’t be any delay in subsequent requests.

    • In certain application servers, you may also precompile JSPs before adding them into JARs. 

  6. Errors

    • If a page fails to translate, an HTTP request for the page should give rise to a 500 (server error) status code communicated back in the HTTP response.

 

Load Class

  • The servlet class generated is loaded using application’s class loader.

 

Instantiate

  • An instance of the servlet class is created.

  • For every servlet mapping declaration of the JSP in the web.xml (similar to servlets), a new instance in addition to the standard JSP file instance is created.  If I have a jsp page in the context root, and I have also registered the same JSP page in web.xml, I will have two instances of that JSP created.

 

jspInit method is called

  • You can override this method.

 

_jspService method is called

  • When requests are made, the container calls the generated servlet’s service(request, response) method, which should call the method _jspService(), passing on the request and response parameters.

  • We should not override _jspService() from our JSP page. This method represents your page source in Java code form—it’s up to the container’s page generators to implementation this method for each individual JSP.

  • However the JSP spec is flexible enough to accommodate any request /response protocol you wish to implement by overriding this method; and for that only you need to override _jspService method.

 

jspDestroy method is called

  • Called before the instance of the JSP servlet is nullified and garbage collected

 

Important points to remember

  • We cannot override servlet lifecycle methods from the JSP code.

  • The servlet class corresponding to the JSP page is created by the container and hence we cannot create a constructor for the JSP page.

Related blog:

 

hibernate interview questions

 

Java 13 Updates revealed Checkout here

 

Java 13 doesn’t have too many major updates which are usually called a JEP (Java Enhancement Proposal). Here is a list of JEPs which were delivered in the new version of Java:

  • Switch Expressions (Preview)
  • Text Blocks (Preview)
  • Reimplement the Legacy Socket API
  • Dynamic CDS Archives
  • ZGC: Uncommit Unused Memory

Most likely, the first two updates are going to be the most interesting for most of Java developers since they introduce new syntax in the Java language.

Switch Expressions (Preview)

Switch expressions have been already introduced in Java 12. Making a long story short, JEP 325 added a new simplified form of a switch which looks like the following:

T result = switch (arg) {
case L1 -> e1;
case L2 -> e2;
default -> e3;
};

If you are not aware of the new syntax, here is an example:

int result = switch (s) {
case "Foo" -> 1;
case "Bar" -> 2;
default -> throw new IllegalArgumentException("Oops!");
};

Java 13 adds a new yield a keyword which allows returning a value from a switch block:

int result = switch (s) {
case "Foo" -> 1;
case "Bar" -> 2;
default -> {
System.out.println("Neither Foo nor Bar, hmmm...");
yield 0;
}
};

Here we can see that a switch an expression can be used to calculate a value for a local variable without assigning the value in each and every case block. The yield the statement is used in the default block to return a value but it can be used in a regular case block.

Now the bad news. You might have noticed the “preview” word in the JEP’s title. It means that the new syntax is not enabled by default in Java 13. If you would like to play with the new switch expressions, you have to run the Java compiler with --enable-preview --release 13 options, and then start your program with --enable-preview option:

$ javac -d classes --enable-preview --release 13 Test.java
$ java -classpath classes --enable-preview Test

Text Blocks (Preview)

Java 13 has another language update. It is text blocks which help to define multi-line strings. For example, an HTML snippet or an SQL query are often defined as a multi-line string in Java. Here is what it usually looks like:

String html = "<html>\n" +
" <body>\n" +
" <p>Hello, world</p>\n" +
" </body>\n" +
"</html>\n";

You might have noticed a lot of \n, + and " characters which make the code a bit longer and harder to read. Some programming languages such Python allow defining multi-line strings by using triple quotes """ to start and end them. Such a language feature may help to make code much nicer. Finally, Java 13 introduces such a feature. Here is how the example above can be re-written using the new text blocks:

String html = """
<html>
<body>
<p>Hello, world</p>
</body>
</html>
""";

At runtime, the string above becomes a usual String (note that the indentation spaces are removed at runtime):

<html>
<body>
<p>Hello, world</p>
</body>
</html>

Although the new text blocks may look simple, there are quite a lot of important topics around it such as line terminators, indentation, incidental white space, escape sequences, concatenation. You can find all the details in JEP 355.

Unfortunately, the new text block is also available only in preview mode.

The rest

JEP 353 replaces the underlying implementation of the java.net.Socket and java.net.ServerSocket APIs. The main motivation for this update wat that the old implementation has several problems and doesn’t fit well to the plans of further Java development.

The Java sockets are the main component for networking. If the update introduces a regression, it’s going to affect many applications. Fortunately, the old implementation was not removed. If something goes wrong, jdk.net.usePlainSocketImpl system property can be used to switch back to the old implementations. However, the old implementation and the system property are going to be removed in one of the next JDK releases.

Next, JEP 351 introduces a new option-XX:ZUncommitDelay for the Z Garbage Collector (ZGC). The option tells ZGC when it should uncommit and return memory to the operating system.

Finally, JEP 350 is an update for application class-data sharing (AppCDS). The JEP the application class-data sharing to allow the dynamic archiving of classes at the end of Java application execution.

Conclusion

Java 13 doesn’t have too many JEPs. Besides major updates, the new Java release has around 2500 bug fixes and minor enhancements. Since the new text blocks and switch expressions are still previewed language features, most likely we won’t see a big difference after migrating to the new Java version.

 

Related blog:

Spring boot tutorial

Digital marketing training in  chennai

What Changes Switch in Function with Java 13 Update

package com.mkyong.java13;

public class JEP354 {

    public static void main(String[] args) {

        System.out.println(getValueViaYield("a"));
        System.out.println(getValueViaYield("c"));
        System.out.println(getValueViaYield("e"));
        System.out.println(getValueViaYield("z"));

    }

    // Traditional switch
    private static int getValueBefore12(String mode) {
        int result;
        switch (mode) {
            case "a":
            case "b":
                result = 1;
                break;
            case "c":
                result = 2;
                break;
            case "d":
            case "e":
            case "f":
                result = 3;
                break;
            default:
                result = -1;
        }
        ;
        return result;
    }

    // Java 12, multiple comma-separated labels
    private static int getValueMultipleLabels(String mode) {
        int result;
        switch (mode) {
            case "a", "b":
                result = 1;
                break;
            case "c":
                result = 2;
                break;
            case "d", "e", "f":
                result = 3;
                break;
            default:
                result = -1;
        }
        ;
        return result;
    }

    // Java 13, value breaks are superseded by 'yield' statements
    // Java 12, switch expression returning value via break
    /*private static int getValueViaBreak(String mode) {
        int result = switch (mode) {
            case "a":
            case "b":
                break 1;
            case "c":
                break 2;
            case "d":
            case "e":
            case "f":
                break 3;
            default:
                break -1;
        };
        return result;
    }*/

    // Java 12, switch expression returning value via label rules (arrow)
    private static int getValueViaArrow(String mode) {
        int result = switch (mode) {
            case "a", "b" -> 1;
            case "c" -> 2;
            case "d", "e", "f" -> 3;
            default -> -1;
        };
        return result;
    }

    // Java 13, switch expression returning value via yield
    private static int getValueViaYield(String mode) {
        int result = switch (mode) {
            case "a", "b":
                yield 1;
            case "c":
                yield 2;
            case "d", "e", "f":
                yield 3;
            default:
                yield -1;
        };
        return result;
    }

}

Output:

1
2
3
-1

Related blog:

Spring boot interview questions

Digital Marketing Strategies that changes the growth

 

1.Because Digital Marketing Levels the Online Playing Field

Gone are the days when business owners still welcome the notion that Digital Marketing is only for the likes of multinationals and large corporations that have the sufficient resources required to mount an online marketing campaign. Digital Marketing actually levels the playing field, providing small and medium enterprises the chance to compete against the big boys and attract their share of targeted traffic.

With digital marketing, small companies now have the resources to perform sales and marketing processes that were previously available only to large corporations. Without a call center, small businesses can engage effectively with multiple customers, even to customers from any parts of the world even if they don’t have physical stores or branches in these locations.

2. Because Digital Marketing Is More Cost-Effective than Traditional Marketing

Small businesses have very little resources and even capitalization. This is why Digital Marketing provides them with a better and much more cost-effective marketing channel that delivers results. Gartner’s Digital Marketing Spend Report highlighted that up to 40% of respondents claimed to get considerable savings by using digital marketing methods of promotion for their products and services.

That is why according to the Gartner survey, 28% of business owners surveyed will shift marketing budget allocations from traditional media channels and invest them into digital online marketing tools and techniques. HubSpot confirms this as shown in the chart below that confirms how digital marketers get better Cost-Per-Lead (CPL) compared to other marketing channels.

3. Because Digital Marketing Delivers Conversion

Businesses marketing products and services online measure success by the percentage rate of incoming traffic gets converted into leads, subscribers or sales, depending on the intended purposes of your website. Without conversion, all your traffic would mean nothing and all your marketing efforts will simply go to waste. That is why business owners are streamlining their digital marketing campaigns towards conversion optimization, making it a top priority above everything else.

There are several tools and techniques that you can use for your digital marketing campaigns such as Search Engine Optimization, social media marketing, and email marketing. As seen from the chart below from HubSpot’s 2013 State of Inbound Marketing Report, these three that generate quick and effective communication and interaction with targeted audiences will deliver better-than-average results in terms of higher conversion rates.

4. Because Digital Marketing Helps Generate Better Revenues

Higher conversion rates generated by effective digital marketing techniques will deliver loads of profitable benefits for you and your business in terms of better and higher revenues. Google confirms this in a study with IPSOS Hong Kong, claiming 2.8 times better revenue growth expectancy for companies using digital marketing strategies to those who do not.

With better revenue growth expectancy, small and medium enterprises using digital marketing techniques will have 3.3 times better chances of expanding their workforce and business — opening their doors to better, larger and farther reaching markets both locally and abroad. Google’s Asia-Pacific Head of SME Kevin O’Kane describes the Internet as rocket fuel for growth for small and medium enterprises.

5. Because Digital Marketing Facilitates Interaction with Targeted Audiences

One of the reasons why digital marketing is taking over traditional marketing channels is the ability of Internet marketing tools to interact with targeted audiences in real-time. I have learned while present digital marketing training in Chennai Engagement in any form is what your customers expect to receive when interacting with your brand or business. How your business handles such engagements and interactions will spell the difference between business success and failure.

Interacting and providing your customers with proper engagement points can give you an insight into what your targeted audiences want. This vital information will steer you towards making the right set of next moves, provide your customers with an even better experience, develop good relationships with them gaining their loyalty and trust that you will need when your business begins to grow.