Welcome to NALIN.

It's all about Technology and Programming.


This blog includes information to the trending technologies, hottest programming tutorials and solution to programming problems.


Do you want to contribute to this blog with your knowledge and skills? If yes, then contact us here


Thank you !!!

5 JSON library for Java Developers

Leave a Comment
The JSON format is one of the most popular formats to transfer and exchange data in web. Almost all RESTful web services take JSON input and provide JSON output but unfortunately JDK doesn't have built-in support for one of the most common web standard like JSON. As a Java developer if you want to develop RESTful web service and produce JSON data or if you are developing a client to an existing RESTFul web services and want to consume JSON response, you don't need to be disappointed. Fortunately, there are so many open source libraries and API available for creating, parsing and processing JSON response in Java e.g. Jackson, Google GSon, json-simple etc.



Actually, there are numerous JSON libraries exists in Java but you don't need to learn all of them, learning just one of them e.g. Jackson should be enough, but, on the other hand, it's worth knowing what are some of the most popular JSON parsing library exists in your disposal.

The JSON is an acronym for JavaScript Object Notation, is a lightweight data-interchange format, an alternative to XML, but smaller, faster and easier to parse. Because JSON uses the JavaScript syntax for describing data objects, it is language and platform independent and many parsers and libraries have been developed over the years.

5 Useful JSON libraries in Java

Here is the list of most useful and essential JSON libraries for Java developers. Though I have used them some or other time or other I mostly prefer Jackson because it's a feature rich and I believe in consistency. It doesn't mean those other libraries are not useful, they also have their own strength e.g. Gson is much simpler to use as compared to Jackson and json-simple is a really light-weight library without any third party dependency.

Jackson

Jackson is a multi-purpose Java library for processing JSON data format. Jackson aims to be the best possible combination of fast, correct, lightweight, and ergonomic for developers.

Jackson offers three methods for processing JSON format, each of them having it’s pros and cons:
  1. Streaming API or incremental parsing/generation: reads and writes JSON content as discrete events
  2. Tree model: provides a mutable in-memory tree representation of a JSON document
  3. Data binding: converts JSON to and from POJO’s
If you are only interested in converting Java object to and from JSON string then the third method is most appropriate for you.

Pros of Jackson is that It provides heaps of features, and looks to be a good tool for reading and writing JSON in a variety of ways, but same time its size becomes a disadvantage if your requirement is just to serialize and deserialize Java object to JSON String.

In order to use Jackson, you can include maven dependency or manually include jackson-core-x.x.x.jar, jackson-databind-x.x.x.jar, and jackson-annotations-x.x.x.jar in Classpath.

GSON

The second Java JSON binding library is Gson, or if you prefer the full name, the google-gson library. Gson is a Java library capable of converting Java objects into their JSON representation and JSON strings to an equivalent Java object without the need for placing Java annotations in your classes.

Some of the salient features of Gson library are:
  1. Provides simple toJson() and fromJson methods to convert Java objects to JSON and vice-versa
  2. Supports arbitrarily complex objects
  3. It has extensive support of Java Generics
  4. Allow custom representation for objects
  5. Allow pre-existing unmodifiable objects to be converted to and from JSON

json-simple

The json-simple is one of the simplest JSON library, also lightweight. You can use this library to encode or decode JSON text. It's an open source lightweight library which is flexible and easy to be used by reusing Map and List interfaces from JDK. A good thing about this library that it has no external dependency and both source and binary are JDK 1.2 compatible.

Pros of Json-simple is that it is lightweight, just 12 classes and it provides support for Java IO readers and writers. You can take your decision better if you know about JSON format i.e.g how information is represented there.

If you are looking for a simple lightweight Java library that reads and writes JSON and supports Streams, json-simple is probably a good match. It does what it says with just 12 classes, and works on legacy (1.4) JREs as well.

In order to use JSON-Simple API, you need to include maven dependency in your project's pom.xml file or alternatively, you can also include following JAR files in your classpath.

Flexjson

Flexjson is another lightweight library for serializing and deserializing Java objects into and from JSON format allowing both deep and shallow copies of objects. The depth to which an object is serialized can be controlled with Flexjson and thus making it similar to lazy-loading, allowing us to extract only the information we need. This is not the case since we want an entire object to be written to file, but it’s good to know that it can do that.

If you know that you are going to use only a small amount of data in your application and you wish to store or read it to and from JSON format, you should consider using Flexjson or Gson.

JSON-lib

JSON-lib is a Java library, based on the work by Douglas Crockford, capable of transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans.

If you are going to use large amounts of data and wish to store or read it to and from JSON format, you should consider using Jackson or JSON-lib.

Double Checked Locking on Singleton Class in Java

Leave a Comment
Singleton class is quite common among Java developers, but it poses many challenges to junior developers. One of the key challenge they face is how to keep Singleton class as Singleton? i.e. how to prevent multiple instances of a Singleton due to whatever reasons. Double checked locking of Singleton is a way to ensure only one instance of Singleton class is created through application life cycle. As name suggests, in double checked locking, code checks for an existing instance of Singleton class twice with and without locking to double ensure that no more than one instance of singleton gets created. By the way, it was broken before Java fixed its memory models issues in JDK 1.5.

Why you need Double checked Locking of Singleton Class?


One of the common scenario, where a Singleton class breaks its contracts is multi-threading. If you ask a beginner to write code for Singleton design pattern, there is good chance that he will come up with something like below :



private static Singleton _instance;
     public static Singleton getInstance() {
          if (_instance == null) {
               _instance = new Singleton();
          }
     return _instance;
}
and when you point out that this code will create multiple instances of Singleton class if called by more than one thread parallel, he would probably make this whole getInstance() method synchronized, as shown in our 2nd code example getInstanceTS() method.

Though it’s a thread-safe and solves issue of multiple instance, it's not very efficient. You need to bear cost of synchronization all the time you call this method, while synchronization is only needed on first class, when Singleton instance is created.

This will bring us to double checked locking pattern, where only critical section of code is locked. Programmer call it double checked locking because there are two checks for _instance == null, one without locking and other with locking (inside synchronized) block.

Here is how double checked locking looks like in Java :


public static Singleton getInstanceDC() {
          if (_instance == null) {
               // Single Checked
               synchronized (Singleton.class) {
                    if (_instance == null) {
                    // Double checked
                    _instance = new Singleton();
               }
          }
     }
     return _instance;
}
On surface this method looks perfect, as you only need to pay price for synchronized block one time, but it still broken, until you make _instance variable volatile.

Without volatile modifier it's possible for another thread in Java to see half initialized state of _instance variable, but with volatile variable guaranteeing happens-before relationship, all the write will happen on volatile _instance before any read of _instance variable.

This was not the case prior to Java 5, and that's why double checked locking was broken before. Now, with happens-before guarantee, you can safely assume that this will work.

That's all about double checked locking of Singleton class in Java.

Factory Design Pattern in Java

Leave a Comment
Factory design pattern in Java one of the core design pattern which is used heavily not only in JDK but also in various Open Source framework such as Spring, Struts and Apache along with decorator design pattern in Java. Factory Design pattern is based on Encapsulation object oriented concept. Factory method is used to create different object from factory often refereed as Item and it encapsulate the creation code. So instead of having object creation code on client side we encapsulate inside Factory method in Java. One of the best examples of factory pattern in Java is BorderFactory Class of Swing API.

What is static factory method or factory design pattern?


Factory design pattern is used to create objects or Class in Java and it provides loose coupling and high cohesion. Factory pattern encapsulate object creation logic which makes it easy to change it later when you change how object gets created or you can even introduce new object with just change in one class. In GOF pattern list Factory pattern is listed as Creation design pattern. Factory should be an interface and clients first either creates factory or get factory which later used to create objects.



Example of static factory method in JDK


Best Example of Factory method design pattern is valueOf() method which is there in String and wrapper classes like Integer and Boolean and used for type conversion i.e. from converting String to Integer or String to double in java..

Some more examples of factory method design pattern from JDK is :

  • valueOf() method which returns object created by factory equivalent to value of parameter passed.
  • getInstance() method which creates instance of Singleton class.
  • newInstance() method which is used to create and return new instance from factory method every time called.
  • getType() and newType() equivalent of getInstance() and newInstance() factory method but used when factory method resides in separate class.

Problem which is solved by Factory method Pattern in Java


Whenever we talk about object oriented language it will based upon some concept like abstraction, polymorphism etc and on that encapsulation and delegation are important concept any design will be called good if task are delegated to different object and some kind of encapsulation is there.



Some time our application or framework will not know that what kind of object it has to create at run-time it knows only the interface or abstract class and as we know we can not create object of interface or abstract class so main problem is frame work knows when it has to create but don’t know what kind of object.

Whenever we create object using new() we violate principle of programming for interface rather than implementation which eventually result in inflexible code and difficult to change in maintenance. By using Factory design pattern in Java we get rid of this problem.

Another problem we can face is class needs to contain objects of other classes or class hierarchies within it; this can be very easily achieved by just using the new keyword and the class constructor. The problem with this approach is that it is a very hard coded approach to create objects as this creates dependency between the two classes.

So factory pattern solve this problem very easily by model an interface for creating an object which at creation time can let its subclasses decide which class to instantiate, Factory Pattern promotes loose coupling by eliminating the need to bind application-specific classes into the code. The factory methods are typically implemented as virtual methods, so this pattern is also referred to as the “Virtual Constructor”. These methods create the objects of the products or target classes.


When to use Factory design pattern in Java

  • Static Factory methods are common in frameworks where library code needs to create objects of types which may be sub classed by applications using the framework.        
  • Some or all concrete products can be created in multiple ways, or we want to leave open the option that in the future there may be new ways to create the concrete product.
  • Factory method is used when Products don't need to know how they are created.
  • We  can use factory pattern where we have to create an object of any one of sub-classes depending on the data provided

Code Example of Factory Design Pattern in Java

Let’s see an example of how factory pattern is implemented in Code.We have requirement to create multiple currency e.g. NRS, SGD, USD and code should be extensible to accommodate new Currency as well. Here we have made Currency as interface and all currency would be concrete implementation of Currency interface. Factory Class will create Currency based upon country and return concrete implementation which will be stored in interface type. This makes code dynamic and extensible.

Here is complete code example of Factory pattern in Java:


interface Currency {
       String getSymbol();
}

// Concrete Rupee Class code
class Rupee implements Currency {
       @Override
       public String getSymbol() {
              return "Rs";
       }
}

// Concrete SGD class Code
class SGDDollar implements Currency {
       @Override
       public String getSymbol() {
              return "SGD";
       }
}

// Concrete US Dollar code
class USDollar implements Currency {
       @Override
       public String getSymbol() {
              return "USD";
       }
}

// Factroy Class code
class CurrencyFactory {

       public static Currency createCurrency (String country) {
       if (country. equalsIgnoreCase ("Nepal")){
              return new Rupee();
       }else if(country. equalsIgnoreCase ("Singapore")){
              return new SGDDollar();
       }else if(country. equalsIgnoreCase ("US")){
              return new USDollar();
        }
       throw new IllegalArgumentException("No such currency");
       }
}

// Factory client code
public class Factory {
       public static void main(String args[]) {
              String country = args[0];
              Currency rupee = CurrencyFactory.createCurrency(country);
              System.out.println(rupee.getSymbol());
       }
}

Advantage of Factory method Pattern in Java:

Factory pattern in Java is heavily used everywhere including JDK, open source library and other frameworks.In following are main advantages of using Factory pattern in Java:

  • Factory method design pattern decouples the calling class from the target class, which result in less coupled and highly cohesive code?

    E.g.: JDBC is a good example for this pattern; application code doesn't need to know what database it will be used with, so it doesn't know what database-specific driver classes it should use. Instead, it uses factory methods to get Connections, Statements, and other objects to work with. Which gives you flexibility to change your back-end database without changing your DAO layer in case you are using ANSI SQL features and not coded on DBMS specific feature?
  • Factory pattern in Java enables the subclasses to provide extended version of an object, because creating an object inside factory is more flexible than creating an object directly in the client. Since client is working on interface level any time you can enhance the implementation and return from Factory.
  • Another benefit of using Factory design pattern in Java is that it encourages consistency in Code since every time object is created using Factory rather than using different constructor at different client side.
  • Code written using Factory design pattern in Java is also easy to debug and troubleshoot because you have a centralized method for object creation and every client is getting object from same place.

Some more advantages of factory method design pattern is:

  • Static factory method used in factory design pattern enforces use of Interface than implementation which itself a good practice. for example:

    Map synchronizedMap = Collections.synchronizedMap(new HashMap());
  • Since static factory method have return type as Interface, it allows you to replace implementation with better performance version in newer release.
  • Another advantage of static factory method pattern is that they can cache frequently used object and eliminate duplicate object creation. Boolean.valueOf() method is good example which caches true and false boolean value.
  • Factory method pattern is also recommended by Joshua Bloch in Effective Java.
  • Factory method pattern offers alternative way of creating object.
  • Factory pattern can also be used to hide information related to creation of object.

forEach() method in Java 8

Leave a Comment
From Java 8 onward, you can iterate over a List or any Collection without using any loop in Java. The new Stream class provides a forEach() method, which can be used to loop over all or selected elements of list and map. forEach() method provides several advantage over traditional for loop e.g. you can execute it in parallel by just using a parallel Stream instead of regular stream. Since you are operating on stream, it also allows you to filter and map elements. Once you are done with filtering and mapping, you can use forEach() to operate over them. You can even use method reference and lambda expression inside forEach() method, resulting in more clear and concise code.



How to use forEach() method in Java 8

Now you know a little bit about the forEach() method and Java 8, it's time to see some code examples and explore more of forEach() method in JDK 8.

Iterating over all elements of List using forEach()

You can loop over all elements using Iterable.forEach() method as shown below:

List<String> alphabets = new ArrayList<>(Arrays.asList("aa", "bbb", "cat", "dog"));
alphabets.forEach(s -> System.out.println(s));

This code will print every element of the list called alphabets. You can even replace lambda expression with method reference because we are passing the lambda parameter as it is to the
System.out.println() method as shown below:

alphabets.forEach(System.out::println);
  
Now, let's see if you want to add comma between two elements than you can do so by using lambda parameters as shown in the following example

alphabets.forEach(s -> System.out.print(s + ","));

But, now you cannot use method reference now because we are doing something with lambda parameters. Let's see another example of forEach() method for doing filtering of elements.

filter and forEach() Example

One of the main features of Stream API is its capability to filter elements based upon some any condition. Let's now only print elements which start with "a", following code will do that for you, startWith() is a method of String class, which return true if String is starting with String "a" or it will return false. Once list is filtered than forEach() method will print all elements starting with  String "a", as shown below:

alphabets.stream()
         .filter(s -> s.startsWith("a"))
         .forEach(System.out::println);

Now, let's filter out only which has length greater than 2, for this purpose we can use the length() function of String class:

alphabets.stream()
         .filter(s -> s.length() > 2)
         .forEach(System.out::println);



forEach() and map() Example

So far you have both basic and advanced example of using the forEach() method, first with simply iterating over each element and then along with using the filter() method, Let's see one more example of forEach() method along with the map() function, which is another key functionality of Stream API.

The map() method of Java 8 allows you to transform one type to another e.g. in our first example we are using map() to transform a list of String to a list of Integer where each element represents the length of String. Now, let's print length of each string using map() function:

alphabets.stream()
         .mapToInt(s -> s.length())
         .forEach(System.out::println);
    
Now how about the calculating sum of the length of all string? You can do so by using fold operations like sum() as shown in the following example:

alphabets.stream()
         .mapToInt(s -> s.length())
         .sum();

These were some of the common but very useful examples of Java 8's forEach() method, a new way to loop over List in Java.

Program to use forEach() function in Java 8

public class Java8Demo {

public static void main(String args[]) {

List<String> alphabets = new ArrayList<>(Arrays.asList("aa", "bbb", "cac", "dog"));

// looping over all elements using Iterable.forEach() method 
alphabets.forEach(s -> System.out.println(s));

// You can even replace lambda expression with method reference 
// because we are passing the lambda parameter as it is to the method 
alphabets.forEach(System.out::println);

// you can even do something with lambda parameter e.g. adding a comma
alphabets.forEach(s -> System.out.print(s + ","));

// There is one more forEach() method on Stream class, which operates
// on stream and allows you to use various stream methods e.g. filter()
// map() etc
alphabets.stream().forEach(System.out::println);

// let's now only print elmements which startswith "a"
alphabets.stream()
.filter(s -> s.startsWith("a"))
    .forEach(System.out::println);

// let's filter out only which has length greater than 2
alphabets.stream()
   .filter(s -> s.length() > 2)
   .forEach(System.out::println);

// now, let's print length of each string using map()
alphabets.stream()
   .mapToInt(s -> s.length())
   .forEach(System.out::println);

// how about calculating sum of length of all string
alphabets.stream()
   .mapToInt(s -> s.length())
   .sum();
}
}

Important things to remember:


1) forEach() is a terminal operation, which means once calling forEach() method on stream, you cannot call another method. It will result in a runtime exception.



2) When you call forEach() on parallel stream, the order of iteration is not guaranteed, but you can ensure that ordering by calling forEachOrdered() method.



3) There are two forEach() method in Java 8, one defined inside Iterable and other inside java.util.stream.Stream class. If purpose of forEach() is just iteration then you can directly call it e.g. list.forEach() or set.forEach() but if you want to perform some operations e.g. filter or map then better first get the stream and then perform that operation and finally call forEach() method.



4) Use of forEach() results in readable and cleaner code.


Threads in Java

Leave a Comment

Why we use Threads in Java?

In short, we use Threads to make Java application faster by doing multiple things at same time. In technical terms, Thread helps you to achieve parallelism in Java program. Since CPU is very fast and nowadays it even contains multiple cores, just one thread is not able to take advantage of all the cores, which means your costly hardware will remain idle for most of the time. By using multiple threads, you can take full advantage of multiple cores by serving more clients and serving them faster.

Since, in today's fast-paced world, response time matters a lot and that's why you have multi-core CPUs, but if your application doesn't make full use of all resources then there is no point adding them, multi-threading is one way to exploiting huge computing power of CPU in Java application. There is one more purpose of using Thread in Java, to doing multiple tasks simultaneously. For example, in GUI application, you want to draw screens at the same time you also want to capture user's action e.g. pressing keys and command and you may want to download or uploading something from the network. If you do all this task in one thread, they would be executed sequentially i.e. first you draw the screen then you capture the command and finally you upload your high score to the network. This may cause a problem for your game or application because GUI seems to be frozen while you doing another task. By using multiple threads in Java you can execute each of this task independently.


Reasons for using Multi-threading in Java


Even Java application contains at least one thread, that is called main thread which executes your main method. There are more threads used by JVM e.g. daemon threads which do garbage collections and some other housekeeping works. As an application developer, you can also add new user threads to make your application faster and more efficient. Here are a couple of common reasons and scenarios to use multiple threads in Java:





To make a task run parallel to another task e.g. drawing and event handling.

GUI applications e.g. Swing and Java FX GUIs are the best examples of multi-threading in Java. In a typical GUI application, the user initiates an action e.g. downloading a file from network or loading games modules from hard disk. These actions require some time to complete but you cannot freeze the GUI because then the user will think your application is hung. Instead, you need a separate thread to carry out the time-consuming task and keep showing relevant messages to the user or allow him to do other tasks at the same time to keep your GUI alive. This is achieved by using multiple threads in Java.


To take full advantage of CPU power.

Another common reason for using multiple threads in Java is to improve throughput of the application by utilizing full CPU power. For example, if you have got 32 core CPU and you are only using 1 of them for serving 1000 clients and assuming that your application is CPU bound, you can improve throughput to 32 times by using 32 threads, which will utilize all 32 cores of your CPU.

For reducing response time.

You can also use multiple threads to reduce response time by doing fast computation by dividing a big problem into smaller chunks and processing them by using multiple threads. For example, the map-reduce pattern is based upon dividing a big problem into smaller one and processing them individually, Java also provides Fork-Join Thread pool for just that purpose.

To sever multiple clients at the same time.

One of the most common scenarios where using multiple threads significantly improve an application's performance is a client-server application. A single threaded application means only one client can connect to the server at a time, but a multi-threaded server means multiple clients can connect to the server at same time. This means next client don't have to wait until your application finish processing request of the previous client.

Like in the following example, you can see that multiple requests are processing by our multi-threaded server at same time.





By the way, Threading is not free, it comes with its own challenges. You can only maximize throughput of your application up to certain extent, once numbering of the thread increases up to a certain threshold, they will start competing for CPU and context switching will occur. Context switching means one thread which is using CPU is suspended and CPU is allocated to another thread for execution. When this happens, thread generally loses all of their cached data. If that thread resumes on another core then it has to build its cache from the start.

Threading also introduces a special set of a problem known as multi-threading issue e.g. deadlock, livelock, memory inconsistency error, race conditions, and starvation. It's also very difficult to test a Java program which involves multiple threads. You cannot predict the order of execution in case of multi-threading and without any synchronization. You should also read Java Concurrency to learn more how to use threads effectively in Java.

Also, parallelism will be limited to the fact of the size of critical section i.e. the part of the code which must be executed by the only thread at a time. If you have a long critical section then eventually all thread will wait there and your program will behave like a single threaded program.

That's all about why use Threads in Java. The fundamental of using a thread is same as using multiple workers to complete a task, but you must remember that not all task can be completed early by just deploying multiple workers e.g. 9 mothers cannot deliver a baby in one month. Similarly, just creating multiple threads to make your program faster will not work. You can only improve performance by dividing CPU bound task to multiple threads e.g. large computations. If your application is IO bound, then you may need to think about other techniques e.g. faster hard disk to improve performance.

You should also consider problems associated with multi-threading because handling synchronization between multiple threads and preventing issues like deadlock, livelock, starvation and memory inconsistency issues are not easy. Often a single thread is what you need because it makes coding easy, you don't need to synchronize anything if your application is single threaded.

applicationContext.xml Vs spring-servlet.xml in Spring Framework

Leave a Comment
If you are a spring developer or new to spring framework then you might have wonder about some query relating to applicationContext.xml and spring-servlet.xml in spring framework. If yes, then don't worry; you are not alone. Many of us have gone through this thoughts at some point of time.

So in this article I am going to make some points that will clear you about the difference between those two files.

First of all, you have to be very clear that in a parent-child hierarchy, spring lets you define multiple contexts. The applicationContext.xml defines the beans for the "root webapp context", i.e. the context associated with the webapp. The spring-servlet.xml defines the beans for one servlet's app context. There can be many of these in a webapp, one per Spring servlet (e.g. spring1-servlet.xml for servlet spring1, spring2-servlet.xml for servlet spring2).

Beans in spring-servlet.xml can reference beans in applicationContext.xml, but not vice versa. All Spring MVC controllers must go in the spring-servlet.xml context. In most simple cases, the applicationContext.xml context is unnecessary. It is generally used to contain beans that are shared between all servlets in a webapp. If you only have one servlet, then there's not really much point, unless you have a specific use for it.

Let's take some scenario to enlight the relation between applicationContext and DispatcherServlet and need of web.xml in the Java application according to it's nature and type.




Scenario 1

In client application (application is not web application, e.g may be swing app).


private static ApplicationContext context = new ClassPathXmlApplicationContext("test-client.xml");

context.getBean(name);

No need of web.xml. ApplicationContext as container for getting bean service. No need for web server container. In test-client.xml there can be Simple bean with no remoting, bean with remoting.

Conclusion: In Scenario 1 applicationContext and DispatcherServlet are not related.


Scenario 2

In a server application (application deployed in server e.g Tomcat). Accessed service via remoting from client program (e.g Swing app)


Define listener in web.xml


<listener>
    <listener-class>
       org.springframework.web.context.ContextLoaderListener
    </listener-class>

</listener>

At server startup ContextLoaderListener instantiates beans defined in applicationContext.xml.

Assuming you have defined the following in applicationContext.xml:

<import resource="test1.xml" />
<import resource="test2.xml" />
<import resource="test3.xml" />

<import resource="test4.xml" />

The beans are instantiated from all four configuration files test1.xml, test2.xml, test3.xml, test4.xml.

Conclusion: In Scenario 2 applicationContext and DispatcherServlet are not related.


Scenario 3

In a web application with spring MVC.


In web.xml define:


<servlet>
    <servlet-name>springweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
</servlet>
<servlet-mapping>
    <servlet-name>springweb</servlet-name>
    <url-pattern>*.action</url-pattern>

</servlet-mapping>

When Tomcat starts, beans defined in springweb-servlet.xml are instantiated. DispatcherServlet extends FrameworkServlet. In FrameworkServlet bean instantiation takes place for springweb . In our case springweb is FrameworkServlet.

Conclusion: In Scenario 3 applicationContext and DispatcherServlet are not related.

Scenario 4

In web application with spring MVC. springweb-servlet.xml for servlet and applicationContext.xml for accessing the business service within the server program or for accessing DB service in another server program.


In web.xml the following are defined:


<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>springweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>springweb</servlet-name>
    <url-pattern>*.action</url-pattern>

</servlet-mapping>

At server startup, ContextLoaderListener instantiates beans defined in applicationContext.xml; assuming you have declared here in:

<import resource="test1.xml" />
<import resource="test2.xml" />
<import resource="test3.xml" />

<import resource="test4.xml" />

The beans are all instantiated from all four test1.xml, test2.xml, test3.xml, test4.xml. After the completion of bean instantiation defined in applicationContext.xml then beans defined in springweb-servlet.xml are instantiated.

So instantiation order is root is application context, then FrameworkServlet.

Now it makes clear why they are important in which scenario.




Lambda expression in Java 8

Leave a Comment
Lambda expressions are included in Java 8 and is one of the big feature of the version. The syntax includes parameter and expression body.

parameter -> expression body

Lambda expression didn't come with just an expression but with different characteristics. Among different characteristics, the important characteristics includes Optional type declaration, Optional parenthesis around parameter, Optional curly braces, Optional return keyword.


  1. Optional type declaration
  2. Optional parenthesis around parameter
  3. Optional curly braces
  4. Optional return keyword
In explanation of above characteristics, we do not have to declare the type of parameter. The compiler can detect the data type from the value itself. Similarly, we do not have to declare parameter in the parenthesis if parameter is single. Parentheses are required for multiple parameters. Furthermore, in expression body, curly braces are not required if the body includes single statement. Finally, if the body includes single expression to return a value then the compiler automatically returns it.






Example:


public class LambdaDemo {



   public static void main(String args[]) {

      LambdaDemo lambda = new LambdaDemo();

      //with type declaration
      MathOperation add = (int x, int y) -> x + y;
      //with out type declaration
      MathOperation sub = (x, y) -> x - y;
      //with return statement along with curly braces
      MathOperation multi = (int x, int y) -> { return x * y; };
      //without return statement and without curly braces
      MathOperation div = (int x, int y) -> x / y;
      System.out.println("10 + 5 = " + lambda.operate(10, 5, addition));
      System.out.println("10 - 5 = " + lambda.operate(10, 5, subtraction));
      System.out.println("10 x 5 = " + lambda.operate(10, 5, multiplication));
      System.out.println("10 / 5 = " + lambda.operate(10, 5, division));
      //without parenthesis
      GreetingService greetServ1 = message ->
      System.out.println("Hello " + message);
      //with parenthesis
      GreetingService greetServ2 = (message) -> {
         System.out.println("Hello " + message);
      }
      greetServ1.sayMessage("Nalin");
      greetServ2.sayMessage("Null In");
   }
   interface MathOperation {
      int operation(int x, int y);
   }
   interface GreetingService {
      void sayMessage(String message);
   }
   private int operate(int a, int b, MathOperation mathOper) {
      return mathOper.operation(a, b);
   }
}