TechDoko

Hot

Post Top Ad

Difference between Executor, ExecutorService and Executers class in Java

All three classes Executor, ExecutorService, and Executers are part of Java's Executor framework which provides thread pool facilities to Java applications. Since creation and management of Threads are expensive and operating system also imposes restrictions on how many threads an application can spawn, it's a good idea is to use a pool of thread to execute tasks in parallel, instead of creating a new thread every time a request come in. This not only improves the response time of application but also prevent resource exhaustion errors like "java.lang.OutOfMemoryError: unable to create new native thread". A thread pool which is created when an application is a startup solves both of these problems. It has ready threads to serve clients when needed and it also has a bound on how many threads to create under load.

From Java 1.5, it was application programmer's responsibility to create and manage such thread pool but from JDK 5 onward Executor framework provides a variety of built-in thread pools in Java e.g. fixed thread pool which contains a fixed number of threads and cached thread pool which can spawn new threads when needed.

The main difference between Executor, ExecutorService, and Executors class is that Executor is the core interface which is an abstraction for parallel execution. It separates task from execution, this is different from java.lang.Thread class which combines both task and its execution. You can read the difference between Thread and Executor to learn more differences between these two key classes of Java.

On the other hand, ExecutorService is an extension of Executor interface and provides a facility for returning a Future object and terminate, or shut down the thread pool. Once the shutdown is called, the thread pool will not accept new task but complete any pending task. It also provides a submit() method which extends Executor.execute() method and returns a Future.

The Future object provides the facility of asynchronous execution, which means you don't need to wait until the execution finishes, you can just submit the task and go around, come back and check if Future object has the result, if execution is completed then it would have result which you can access by using the Future.get() method. Just remember that this method is a blocking method i.e. it will wait until execution finish and the result is available if it's not finished already.

By using the Future object returned by ExecutorService.submit() method, you can also cancel the execution if you are not interested anymore. It provides cancel() method to cancel any pending execution.

Third one Executors is a utility class similar to Collections, which provides factory methods to create different types of thread pools e.g. fixed and cached thread pools. Let's see some more difference between these three classes.

Executor vs ExecutorService vs Executors in Java

As already mentioned, all three classes are part of Java 1.5 Executor framework and it's very important for a Java programmer to learn and understand about these classes to make effective use of different types of thread pools provided by Java. Let's see some key differences between Executor, ExecutorService, and Executors in Java to understand them better:

1) One of the key difference between Executor and ExecutorService interface is that former is a parent interface while ExecutorService extends Executor i.e. it's a sub-interface of Executor.

2) Another important difference between ExecutorService and Executor is that Executor defines execute() method which accepts an object of the Runnable interface, while submit() method can accept objects of both Runnable and Callable interfaces.

3) The third difference between Executor and ExecutorService interface is that execute() method doesn't return any result, its return type is void but submit() method returns the result of computation via a Future object. This is also the key difference between submit() and execute() method, which is one of the frequently asked Java concurrency interview questions.

4) The fourth difference between ExecutorService and Executor interface is that apart from allowing a client to submit a task, ExecutorService also provides methods to control the thread pool e.g. terminate the thread pool by calling the shutDown() method.

5) Executors class provides factory methods to create different kinds of thread pools e.g. newSingleThreadExecutor() creates a thread pool of just one thread, newFixedThreadPool(int numOfThreads) creates a thread pool of fixed number of threads and newCachedThreadPool() creates new threads when needed but reuse the existing threads if they are available.
Read More

Reading XML file in java using SAX Parser

Reading XML file in java using SAX Parser is little different than reading xml file in Java with DOM parser which we had discussed in last article of this series. This tutorial is can be useful for those who are new to the java world and got the requirement for read an xml file in java in their project or assignment, key feature of java is it provides built in class and object to handle everything which makes our task very easy. Basically this process of handling XML file is known as parsing means break down the whole string into small pieces using the special tokens.

Parsing can be done using two ways:
- Using DOM Parser
- Using SAX Parser

Read XML file in Java Using SAX Parser Example

In DOM parser we have to follow simple three steps:

- Parse the XML file
- Create the java object
- Manipulate the object means we can read that object or add them to list or whatever function we want we can do

But in SAX Parser its little bit different.

SAX Parser: It’s an event based parsing it contains default handler for handling the events whenever SAX parser pareses the xml document and it finds the Start tag “<” and end tag”>” it calls corresponding handler method.

Though there are other ways also to get data from xml file e.g. using XPATH in Java which is a language like SQL and give selective data from xml file.

Sample Example of reading XML File – SAX Parser

Suppose we have this sample XML file bank.xml which contains account details of all accounts in a hypothetical bank:

     
            1001
            Jack Robinson
            10000
     
     
            1002
            Sony Corporation
            1000000
     

1. Create the SAX parser and parse the XML file: In this step we will take one factory instance from SAXParserFactory to parse the xml  file this factory instance in turns  give us instance of parser using the parse() method will parse the Xml file.

2. Event Handling: when Sax Parser starts the parsing whenever it founds the start or end tag it will invoke the corresponding event handling method which is public void startElement (…) and public void end Element (...).

3. Register the events: The class extends the Default Handler class to listen for callback events and we register this handler to sax Parser to notify us for call back event.

Let see java code for all these steps. To represent data from our sample xml file we need one java domain object called Account and sample code for implementing SAX parser in Java :

Advantage of SAX parser in Java:

It is faster than DOM parser because it will not load the XML document into the memory .its an event based.
Read More

Synchronized block and method in Java

Synchronized block and synchronized methods are two ways to use synchronized keyword in Java and implement mutual exclusion on critical section of code. Since Java is mainly used to write multi-threading programs,  which present various kinds of thread related issues like thread-safety, deadlock and race conditions, which plagues into code mainly because of poor understanding of synchronization mechanism provided by Java programming language. Java provides inbuilt synchronized and volatile keyword to achieve synchronization in Java. Main difference between synchronized method and synchronized block is selection of lock on which critical section is locked. Synchronized method depending upon whether its a static method or non static locks on either class level lock or object lock. Class level lock is one for each class and represented by class literal e.g. Stirng.class. Object level lock is provided by current object e.g. this instance, You should never mix static and non static synchronized method in Java.. On the other hand synchronized block locks on monitor evaluated by expression provided as parameter to synchronized block. In next section we will see an example of both synchronized method and synchronized block to understand this difference better.

Difference between synchronized method vs block in Java

Here are Some more differences between synchronized method and block in Java based upon experience and syntactical rules of synchronized keyword in Java. Though both block and method can be used to provide highest degree of synchronization in Java, use of synchronized block over method is considered as better Java coding practices.

1) One significant difference between synchronized method and block is that, Synchronized block generally reduce scope of lock. As scope of lock is inversely proportional to performance, its always better to lock only critical section of code. One of the best example of using synchronized block is double checked locking in Singleton pattern where instead of locking whole getInstance() method we only lock critical section of code which is used to create Singleton instance. This improves performance drastically because locking is only required one or two times.

2) Synchronized block provide granular control over lock, as you can use arbitrary any lock to provide mutual exclusion to critical section code. On the other hand synchronized method always lock either on current object represented by this keyword  or class level lock, if its static synchronized method.

3) Synchronized block can throw throw java.lang.NullPointerException if expression provided to block as parameter evaluates to null, which is not the case with synchronized methods.

4) In case of synchronized method, lock is acquired by thread when it enter method and released when it leaves method, either normally or by throwing Exception. On the other hand in case of synchronized block, thread acquires lock when they enter synchronized block and release when they leave synchronized block.

Synchronized method vs synchronized block Example in Java

Here is an example of  sample class which shows on which object synchronized method and block are locked and how to use them :

That's all on difference between synchronized method and block in Java. Favoring synchronized block over method is one of the Java best practices to follow as it reduces scope of lock and improves performance. On the other hand using synchronized method are rather easy but it also creates bugs when you mix non static and static synchronized methods, as both of them are locked on different monitors and if you use them to synchronize access of shared resource, it will most likely break.
Read More

Double Checked Locking on Singleton Class in Java

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.
Read More

Creating a memory leak with Java.

Here's a good way to create a true memory leak (objects inaccessible by running code but still stored in memory) in Java:

1. The application creates a long-running thread (or use a thread pool to leak even faster).
2. The thread loads a class via an (optionally custom) ClassLoader.
3. The class allocates a large chunk of memory (e.g. new byte[1000000]), stores a strong reference to it in a static field, and then stores a reference to itself in a ThreadLocal. Allocating the extra memory is optional (leaking the Class instance is enough), but it will make the leak work that much faster.
4. The thread clears all references to the custom class or the ClassLoader it was loaded from.
5. Repeat.

This works because the ThreadLocal keeps a reference to the object, which keeps a reference to its Class, which in turn keeps a reference to its ClassLoader. The ClassLoader, in turn, keeps a reference to all the Classes it has loaded.

(It was worse in many JVM implementations, especially prior to Java 7, because Classes and ClassLoaders were allocated straight into permgen and were never GC'd at all. However, regardless of how the JVM handles class unloading, a ThreadLocal will still prevent a Class object from being reclaimed.)

A variation on this pattern is why application containers (like Tomcat) can leak memory like a sieve if you frequently redeploy applications that happen to use ThreadLocals in any way. (Since the application container uses Threads as described, and each time you redeploy the application a new ClassLoader is used.)
Read More

Issue analysis and solved : No mapping found for HTTP request with URI [/WEB-INF/views/home.html] in DispatcherServlet with name 'appServlet'.

WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/WEB-INF/views/home.html] in DispatcherServlet with name 'appServlet'

I got above PageNotFound (ERROR 404) message while loading home.html page in Spring Web MVC project with Google App Engine nature. But when I use home.jsp then it works fine.

Then I searched and analysed how the flow of servlet container goes through the request.

1. First the DispatcherServlet is invoked by the Servlet Container.

2. The DispatcherServlet finds a mapping which maps to the home method of the Controller and the home method returns a view name "home".

3.Now the DispatcherServlet uses a View Resolver (InternalResourceViewResolver) to find the View to render the model through, since the name is "home", this maps to the /WEB-INF/view/home.html view.

4. Now essentially a call is made to RequestDispatcher.forward("/WEB-INF/views/home.html")

5. The Servlet container at this point tries to find the servlet which can handle /WEB-INF/views/home.html uri - if it had been a .jsp there is a JSPServlet registered which can handle rendering the jsp, however for *.html there is no servlet registered, so the call ends up with the "default servlet", which is registered with a servlet-mapping of / which probably the DispatcherServlet is.

6. Now the Dispatcher servlet does not find a controller to handle request for /WEB-INF/views/home.html and hence the message that I saw during project run.

If you are also getting this type of error and you want this kind of a extension to be handled by the servlet container, say tomcat, you can register *.html extension to be handled by JSPServlet and then it should work cleanly. Or return forward:/resources/HelloWorld.html which will be considered a static file relative to your resources folder.

And one of my friend asked how he would register *.html extension to be handled by JSPServlet. So, I told him that it can be achieved in two simple steps.

1. By adding this servletmapping for the JSP servlet.

jsp
*.html

This tells the application container to use the the JSP servlet when serving html files.

2. Comment out the for text/html mime type (*.html) files so that the container won't handle HTML files as static content.

Happy Debugging !
Read More

Difference between Setter vs Constructor Injection in Spring.

Spring Setter vs Constructor Injection

Spring supports two types of dependency Injection, using setter method e.g. setXXX() where XXX is a dependency or via a constructor argument. The first way of dependency injection is known as setter injection while later is known as constructor injection. Both approaches of Injecting dependency on Spring bean has there pros and cons, which we will see in this Spring framework article.

Difference between Setter and Constructor Injection in Spring framework

Spring supports both setter and constructor Injection which are two standard way of injecting dependency on beans managed by IOC constructor. Spring framework doesn't support Interface Injection on which dependency is injected by implementing a particular interface. In this section we will see a couple of difference between setter and constructor Injection, which will help you decide when to use setter Injection over constructor Injection in Spring and vice-versa.

1) The fundamental difference between setter and constructor injection, as their name implies is How dependency is injected.  Setter injection in Spring uses setter methods like setDependency() to inject dependency on any bean managed by Spring's IOC container. On the other hand constructor injection uses constructor to inject dependency on any Spring-managed bean.

2) Because of using setter method, setter Injection in more readable than constructor injection in Spring configuration file usually applicationContext.xml . Since setter method has name e.g. setReporotService() by reading Spring XML config file you know which dependency you are setting. While in constructor injection, since it uses an index to inject the dependency, it's not as readable as setter injection and you need to refer either Java documentation or code to find which index corresponds to which property.

3) Another difference between setter vs constructor injection in Spring and one of the drawback of  setter injection is that it does not ensures dependency Injection. You can not guarantee that certain dependency is injected or not, which means you may have an object with incomplete dependency. On other hand constructor Injection does not allow you to construct object, until your dependencies are ready.


4) One more drawback of setter Injection is Security. By using setter injection, you can override certain dependency which is not possible which is not possible with constructor injection because every time you call the constructor, a new object is gets created.

When to use Setter Injection over Constructor Injection in Spring

Setter Injection has upper hand over Constructor Injection in terms of readability. Since for configuring Spring we use XML files, readability is much bigger concern. Also drawback of setter Injection around ensuring mandatory dependency injected or not can be handled by configuring Spring to check dependency using "dependency-check" attribute of  tag or tag. Another worth noting point to remember while comparing Setter Injection vs Constructor Injection is that, once number of dependency crossed a threshold e.g. 5 or 6 its handy manageable to passing dependency via constructor. Setter Injection is preferred choice when number of dependency to be injected is lot more than normal, if some of those arguments is optional than using Builder design pattern is also a good option.
Read More