Saturday, 29 September 2018

Difference Between yield And sleep in Java Multi-Threading

Difference between yield() and sleep() methods in Java is a very frequently asked Java multi-threading interview question. As both of the methods are related to pausing the currently executing thread so it does create some confusion. In this post let's see the differences between yield() and sleep() methods to have clarity over the usage.

Please keep in mind that both yield() and sleep() are static methods of the Java Thread class. When called both of these methods will work on the currently executing thread, not on any particular thread.

As example if there are three threads running T1, T2 and T3. Calling Thread.sleep() or Thread.yield() will work on whichever thread is currently executing. You can't say T1.sleep() or T3.yield() to put T1 thread to sleep or T3 thread to yield.


yield() method in Java

Calling yield() method is a hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint. If the hint is not ignored then the executing thread is suspended and the CPU is given to some other runnable thread.

The suspended thread will wait until the CPU becomes available again. Technically, in process scheduler's terminology, the executing thread is put back into the ready queue of the processor and waits for its next turn.

According to JavaDOC - http://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#yield--
It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.

Java yield() method example

In this example code three threads are spawned. In the run method there is a loop which runs 3 times printing value of variable i. Currently executing thread is asked to yield when value of i is 1, that gives another thread to start execution.

public class YieldDemo {

    public static void main(String[] args) {
        YieldClass yc = new YieldClass();
        Thread thread1 = new Thread(yc, "Thread1");
        Thread thread2 = new Thread(yc, "Thread2");
        Thread thread3 = new Thread(yc, "Thread3");
        thread1.start();
        thread2.start();
        thread3.start();
        
        try {
            thread1.join();
         
            thread2.join();
            thread3.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Execution finished");
    }
}

class YieldClass implements Runnable{
    
    @Override
    public void run() {
        System.out.println("Executing run for Thread - " + Thread.currentThread().getName());
          for(int i = 0; i < 3; i++){
              System.out.println("i " + i + "Thread- " + Thread.currentThread().getName());
                if(i == 1){
                    System.out.println("Yielding thread : "+ 
                         Thread.currentThread().getName());
                     Thread.yield();
                }
          }   
    }  
}

Output

Executing run for Thread - Thread1
Executing run for Thread - Thread2
i 0Thread- Thread1
i 0Thread- Thread2
i 1Thread- Thread1
i 1Thread- Thread2
Yielding thread : Thread1
Yielding thread : Thread2
Executing run for Thread - Thread3
i 0Thread- Thread3
i 1Thread- Thread3
Yielding thread : Thread3
i 2Thread- Thread1
i 2Thread- Thread2
i 2Thread- Thread3
Execution finished

It can be seen from the output how Thread 1 and Thread 2 are interleaving and they both are printing value of i as 0 and 1. At that point yield method is called that gives a chance to Thread 3 to start its execution.

sleep() method in Java

sleep() method causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

Java sleep() method example

In this example code three threads are spawned. In the run method there is a loop which runs 3 times printing value of variable i. sleep() method is called on the currently executing thread when value of i is 1 with argument as 100, which causes the current thread to sleep for 100 milliseconds.

public class SleepDemo {

    public static void main(String[] args) {
    
            SleepClass yc = new SleepClass();
            Thread thread1 = new Thread(yc, "Thread1");
            Thread thread2 = new Thread(yc, "Thread2");
            Thread thread3 = new Thread(yc, "Thread3");
            thread1.start();
            thread2.start();
            thread3.start();
            
            try {
                thread1.join();
             
                thread2.join();
                thread3.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("Execution finished");
        }
}

class SleepClass implements Runnable{
    
    @Override
    public void run() {
        System.out.println("Executing run for Thread - " + Thread.currentThread().getName());
        //synchronized(this){
          for(int i = 0; i < 3; i++){
              System.out.println("i " + i + "Thread- " + Thread.currentThread().getName());
                if(i == 1){
                    System.out.println("Going to sleep thread : "+ 
                         Thread.currentThread().getName());
                     try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        //}            
    } 
}

Output

Executing run for Thread - Thread1
Executing run for Thread - Thread2
i 0Thread- Thread1
i 0Thread- Thread2
i 1Thread- Thread1
i 1Thread- Thread2
Going to sleep thread : Thread1
Going to sleep thread : Thread2
Executing run for Thread - Thread3
i 0Thread- Thread3
i 1Thread- Thread3
Going to sleep thread : Thread3
i 2Thread- Thread2
i 2Thread- Thread1
i 2Thread- Thread3
Execution finished

yield() Vs sleep() in Java

Based on these descriptions of sleep and yield one of the difference between yield() and sleep() methods is that a thread which has yielded may become eligible to run again as soon as it has yielded if there is no other thread with the same or more thread priority.

Where as in case of sleep() the thread will definitely go to sleep for the specified time (unless it is interrupted) and in the meantime another thread (of less or more priority) can start its execution.

Calling yield() and sleep() methods from synchronized context

Another important point to note here is, if yield() or sleep() method is invoked on the current thread, the current thread doesn't have to give up the locks it is holding if called from the synchronized context, as in the case with wait method.

yield() with synchronized example

Here I am using the same code as above just kept the for loop inside a synchronized block.

public class YieldDemo {
    public static void main(String[] args) {
        YieldClass yc = new YieldClass();
        Thread thread1 = new Thread(yc, "Thread1");
        Thread thread2 = new Thread(yc, "Thread2");
        Thread thread3 = new Thread(yc, "Thread3");
        thread1.start();
        thread2.start();
        thread3.start();
        
        try {
            thread1.join();
         
            thread2.join();
            thread3.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Execution finished");
    }
}

class YieldClass implements Runnable{
    
    @Override
    public void run() {
        System.out.println("Executing run for Thread - " + Thread.currentThread().getName());
        synchronized(this){
          for(int i = 0; i < 3; i++){
              System.out.println("i " + i + "Thread- " + Thread.currentThread().getName());
                if(i == 1){
                    System.out.println("Yielding thread : "+ 
                         Thread.currentThread().getName());
                     Thread.yield();
                }
            }
        }  
    } 
}

Output

Executing run for Thread - Thread1
Executing run for Thread - Thread2
i 0Thread- Thread1
i 1Thread- Thread1
Yielding thread : Thread1
Executing run for Thread - Thread3
i 2Thread- Thread1
i 0Thread- Thread3
i 1Thread- Thread3
Yielding thread : Thread3
i 2Thread- Thread3
i 0Thread- Thread2
i 1Thread- Thread2
Yielding thread : Thread2
i 2Thread- Thread2
Execution finished

It can be seen how "Executing run for Thread" message is printed for both Thread-1 and Thread-2 but only Thread-1 enters the synchronized block. Thread-1 yields after value of i becomes 1. But again Thread-1 is executed as it is the thread currently holding the lock. Only after it releases the lock another thread starts its execution.

sleep() with synchronized example

public class SleepDemo {

    public static void main(String[] args) {
    
            SleepClass yc = new SleepClass();
            Thread thread1 = new Thread(yc, "Thread1");
            Thread thread2 = new Thread(yc, "Thread2");
            Thread thread3 = new Thread(yc, "Thread3");
            thread1.start();
            thread2.start();
            thread3.start();
            
            try {
                thread1.join();
             
                thread2.join();
                thread3.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("Execution finished");
        }
}

class SleepClass implements Runnable{
    
    @Override
    public void run() {
        System.out.println("Executing run for Thread - " + Thread.currentThread().getName());
        synchronized(this){
          for(int i = 0; i < 3; i++){
              System.out.println("i " + i + "Thread- " + Thread.currentThread().getName());
                if(i == 1){
                    System.out.println("Going to sleep thread : "+ 
                         Thread.currentThread().getName());
                     try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }  
    }  
}

Output

Executing run for Thread - Thread1
i 0Thread- Thread1
i 1Thread- Thread1
Going to sleep thread : Thread1
Executing run for Thread - Thread3
Executing run for Thread - Thread2
i 2Thread- Thread1
i 0Thread- Thread2
i 1Thread- Thread2
Going to sleep thread : Thread2
i 2Thread- Thread2
i 0Thread- Thread3
i 1Thread- Thread3
Going to sleep thread : Thread3
i 2Thread- Thread3
Execution finished

That's all for this topic Difference Between yield and sleep in Java Multi-Threading. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Creating Thread in Java
  2. Thread States in Java Multi-Threading
  3. Inter-thread Communication Using wait, notify And notifyAll - Java Multithreading
  4. ThreadLocal Class in Java
  5. Volatile in Java

You may also like -

  1. Abstraction in Java
  2. CopyOnWriteArrayList in Java
  3. Difference Between Checked & Unchecked Exception in Java
  4. interface static methods in Java 8
  5. fail-fast Vs fail-safe iterator in Java
  6. Lambda expression and variable scope
  7. How to Find First Non-Repeated Character in a Given String - Java Program
  8. Just In Time Compiler (JIT) in Java

CountDownLatch in Java Concurrency

There are scenarios in an application when you want one or more threads to wait until one or more events being performed in other threads complete. CountDownLatch in Java concurrent API helps in handling such scenarios.

Note that CountDownLatch was introduced in Java 5 along with other concurrent classes like CyclicBarrier, ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue with in java.util.Concurrent package.


How CountDownLatch is used

CountDownLatch in Java, as the name suggests, can be visualized as a latch that is released only after the given number of events occur.

When an instance of CountDownLatch is created it is initialized with a count. This count denotes the number of times countDown() must be invoked before waiting threads can pass through the latch.

Note that a CountDownLatch initialized to N can be used either ways-
  • To make one thread wait until N threads have completed some action, or
  • Some action has been completed N times (may be by a single thread).

Each time one of those events occur count is decremented using the countdown() method of the CountDownLatch class. Waiting threads are released when the count reaches zero.

Thread(s) that are waiting for the latch to release are blocked using await() method.

Java CountDownLatch Constructor

CountDownLatch(int count)

Constructs a CountDownLatch initialized with the given count. Here count specifies the number of events that must happen in order for the latch to open.

await() and countdown() methods in CountDownLatch class

await() and countdown() are two main methods in CountDownLatch class which control the working of the latch.

await() method- A thread that waits on the latch to open calls await() method, await() method has two forms.

public void await() throws InterruptedException

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted. If the current count is zero then this method returns immediately.

If the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happen:

  • The count reaches zero due to invocations of the countDown() method
  • Some other thread interrupts the current thread.
public boolean await(long timeout, TimeUnit unit) throws InterruptedException

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted, or the specified waiting time elapses, the waiting time is specified by an object of TimeUnit enumeration.

If the current count is zero then this method returns immediately with the value true. If the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happen:

  • The count reaches zero due to invocations of the countDown() method.
  • Some other thread interrupts the current thread.
  • The specified waiting time elapses.

countdown() method- Threads which are executing the events signal the completion of the event by calling countDown() method.

public void countDown()

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

CountDownLatch Java Example program

That's a lot of theory so let's see an example to make it clearer and see how await(), countdown() and the constructor to provide count are actually used.

Let's take a scenario where your application needs to read 3 files, parse the read lines and only after reading and parsing all the three files the application should move ahead to do some processing with the parsed objects.
So here we'll have three separate threads reading three separate files and the main thread awaits until all the three threads finish and call countdown().

public class CountdownlatchDemo {

    public static void main(String[] args) {
        CountDownLatch cdl = new CountDownLatch(3);
        // Initializing three threads to read 3 different files.
        Thread t1 = new Thread(new FileReader("thread-1", "file-1", cdl));
        Thread t2 = new Thread(new FileReader("thread-2", "file-2", cdl));
        Thread t3 = new Thread(new FileReader("thread-3", "file-3", cdl));
        t1.start();
        t2.start();
        t3.start();
        try {
            // main thread waiting till all the files are read
            cdl.await();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Files are read ... Start further processing");
    }

}

class FileReader implements Runnable {
    private String threadName;
    private String fileName;
    private CountDownLatch cdl;
    FileReader(String threadName, String fileName, CountDownLatch cdl){
        this.threadName = threadName;
        this.fileName = fileName;
        this.cdl = cdl;        
    }
    @Override
    public void run() {
        System.out.println("Reading file " + fileName + " thread " + threadName);
        // do countdown here
        cdl.countDown();
    } 
}

Output

Reading file file-1 thread thread-1
Reading file file-3 thread thread-3
Reading file file-2 thread thread-2
Files are read ... Start further processing

Here it can be seen that inside main() method, CountDownLatch instance cdl is created with an initial count of 3. Then three instances of FileReader are created that start three new threads. Then the main thread calls await() on cdl, which causes the main thread to wait until cdl count has been decremented three times. Notice that cdl instance is passed as a parameter to the FileReader constructor that cdl instance is used to call countdown() method in order to decrement the count. Once the countdown reaches zero, the latch opens allowing the main thread to resume.

You can comment the code where await() is called, then main thread will resume even before all the 3 files are read, so you see in these type of scenarios where you want the thread to resume only after certain events occur then CountDownLatch is a powerful synchronization aid that allows one or more threads to wait for certain events to finish in other threads.

From the above example if you got the feeling that whatever count you have given in the CountDownLatch, you should spawn the same number of threads for countdown then that is a wrong understanding. As I have mentioned it depends on the number of events, so you can very well have a single thread with a loop and decrementing the count there.

Let's change the example used above to have single thread and use for loop to countdown.

public class CountdownlatchDemo {

    public static void main(String[] args) {
        CountDownLatch cdl = new CountDownLatch(3);
        // Initializing three threads to read 3 different files.
        Thread t1 = new Thread(new FileReader("thread-1", "file-1", cdl));
        /*Thread t2 = new Thread(new FileReader("thread-2", "file-2", cdl));
        Thread t3 = new Thread(new FileReader("thread-3", "file-3", cdl));*/
        t1.start();
        /*t2.start();
        t3.start();*/
        try {
            // main thread waiting till all the files are read
            cdl.await();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Files are read ... Start further processing");
    }
}

class FileReader implements Runnable {
    private String threadName;
    private String fileName;
    private CountDownLatch cdl;
    FileReader(String threadName, String fileName, CountDownLatch cdl){
        this.threadName = threadName;
        this.fileName = fileName;
        this.cdl = cdl;        
    }
    @Override
    public void run() {
        for(int i = 0; i < 3; i++){
            System.out.println("Reading file " + fileName + " thread " + threadName);
            // do countdown here
            cdl.countDown();
        }
    }
}

Output

Reading file file-1 thread thread-1
Reading file file-1 thread thread-1
Reading file file-1 thread thread-1
Files are read ... Start further processing

Here you can see that only a single thread is used and countdown is done on the number of events. So it is true both ways. A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.

Usage of CountDownLatch in Java

As you have seen in the example you can use CountDownLatch when you want to break your code in such a way that more than one thread can process the part of the code but you can start further processing only when all the threads which are working on some part of the code have finished. Once all the threads have finished main thread can come out of the await (as the latch is released) and start further processing.

You can also use CountDownLatch to test concurrency by giving a certain count in the CountDownLatch Constructor and start that many threads. Also there may be more than one waiting thread, so that scenario how waiting threads behave once the countdown reaches zero (as all of them will be released at once) can also be tested.

If you have some external dependencies and once all the dependencies are up and running then only you should start processing in your application. That kind of scenario can also be handled with CountDownLatch.

CountDownLatch in Java can not be reused

One point to remember is CountDownLatch cannot be reused. Once the countdown reaches zero any further call to await() method won't block any thread. It won't throw any exception either.

Let's see an example. We'll use the same example as above and spawn 3 more threads once the first three set of threads are done.

public class CountdownlatchDemo {

    public static void main(String[] args) {
        CountDownLatch cdl = new CountDownLatch(3);
        // Initializing three threads to read 3 different files.
        Thread t1 = new Thread(new FileReader("thread-1", "file-1", cdl));
        Thread t2 = new Thread(new FileReader("thread-2", "file-2", cdl));
        Thread t3 = new Thread(new FileReader("thread-3", "file-3", cdl));
        t1.start();
        t2.start();
        t3.start();
        try {
            // main thread waiting till all the files are read
            cdl.await();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Files are read ... Start further processing");
        Thread t4 = new Thread(new FileReader("thread-4", "file-4", cdl));
        Thread t5 = new Thread(new FileReader("thread-5", "file-5", cdl));
        Thread t6 = new Thread(new FileReader("thread-6", "file-6", cdl));
        t4.start();
        t5.start();
        t6.start();
        try {
            // main thread waiting till all the files are read
            cdl.await();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Files are read again ... Start further processing");
    }
}

class FileReader implements Runnable {
    private String threadName;
    private String fileName;
    private CountDownLatch cdl;
    FileReader(String threadName, String fileName, CountDownLatch cdl){
        this.threadName = threadName;
        this.fileName = fileName;
        this.cdl = cdl;        
    }
    @Override
    public void run() {
        System.out.println("Reading file " + fileName + " thread " + threadName);
        // do countdown here
        cdl.countDown();
    }
}

Output

Reading file file-2 thread thread-2
Reading file file-3 thread thread-3
Reading file file-1 thread thread-1
Files are read ... Start further processing
Files are read again ... Start further processing
Reading file file-4 thread thread-4
Reading file file-6 thread thread-6
Reading file file-5 thread thread-5

Here note that await() is called again after starting thread4, thread5 and thread6 but it doesn't block main thread as it did for the first three threads. "Files are read again ... Start further processing" is printed even before the next three threads are processed. Another concurrent utility CyclicBarrier can be resued infact that is one of the difference between CountDownLatch and CyclicBarrier.

Points to note

  • A CountDownLatch initialized to N, using its constructor, can be used to make one (or more) thread wait until N threads have completed some action, or some action has been completed N times.
  • countDown() method is used to decrement the count, once the count reaches zero the latch is released.
  • await() method is used to block the thread(s) waiting for the latch to release.
  • CountDownLatch cannot be reused. Once the countdown reaches zero any further call to await() method won't block any thread.

That's all for this topic CountDownLatch in Java Concurrency. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between CountDownLatch And CyclicBarrier in Java
  2. ConcurrentHashMap in Java
  3. AtomicInteger in Java Concurrency
  4. ConcurrentSkipListMap in Java
  5. Java Concurrency Interview Questions

You may also like -

  1. Synchronization in Java multithreading
  2. ThreadLocal class in Java
  3. How to remove duplicate elements from an ArrayList in Java
  4. Difference Between Comparable and Comparator in Java
  5. Creating Custom Exception Class in Java
  6. Garbage Collection in Java
  7. How to Create Immutable Class in Java
  8. finalize method in Java

Spring MVC Configuring Multiple View Resolvers Example

In this post we’ll see how to configure multiple view resolvers with in Spring MVC application. In Spring MVC view resolver is used to resolve the view name without actually hardcoding the view file. That way you are not tightly coupled with a specific view technology.

Spring MVC framework also provides the flexibility to configure more than one view resolver.

Technologies used

Following is the list of tools used for this Spring MVC configuring multiple view resolvers example.

  • Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  • Java 10
  • Tomcat server V 9.0.10
  • Eclipse Photon 4.8.0 for Java EE development (This Eclipse version supports Java 10)

Spring MVC Project structure using Maven


Spring MVC configuring multiple view resolvers example

In this example we’ll configure three different view resolvers in our Spring MVC application to show multiple view resolvers in action. We’ll show both ways of configuration – XML configuration and Java Config.

Three View resolvers that are configured in the Spring MVC application are the following ones-

  • BeanNameViewResolver- A simple implementation of ViewResolver that interprets a view name as a bean name in the current application context.
  • ResourceBundleViewResolver- Implementation of ViewResolver that uses bean definitions in a ResourceBundle, specified by the bundle base name, and for each view it is supposed to resolve, it uses the value of the property [viewname].(class) as the view class and the value of the property [viewname].url as the view url.
  • InternalResourceViewResolver- A subclass of UrlBasedViewResolver that supports InternalResourceView (in effect, Servlets and JSPs) and subclasses such as JstlView and TilesView.

Spring MVC configuring multiple view resolvers – XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">
        
     <mvc:annotation-driven />
     <!-- <mvc:annotation-driven validator="validator"/> -->
     <context:component-scan base-package="org.netjs.controller" />
     <bean id="BeanViewResolver" class=
        "org.springframework.web.servlet.view.BeanNameViewResolver">
        <property name="order" value="0"/>
     </bean>
     <bean id="ResourceResolver" class=
        "org.springframework.web.servlet.view.ResourceBundleViewResolver">
         <property name="order" value="1"/>
        <property name="basename" value="views"/>
    </bean>
     <bean id="JSPViewResolver" class=
        "org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="2"/>
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
     <bean name="beanView" class="org.netjs.config.CustomView" />
</beans>

BeanNameViewResolver Spring configuration

Since BeanNameViewResolver interprets a view name as a bean name in the application context that is why there is this bean definition-

<bean name="beanView" class="org.netjs.config.CustomView" />

Corresponding handler method in the Controller class is as follows-

 @RequestMapping(value = "/showMsg", method = RequestMethod.GET)
 public String showMessage(Model model) throws Exception{
  model.addAttribute("msg", "Configuring multiple view resolver example");
  return "beanView";
 }

From the handler method view name is returned as “beanView” which means View for this handler method resolves to CustomView class.

CustomView class

CustomView class implements View interface and provides implementation of the render() method which is used to render view.

public class CustomView implements View {
    
    @Override
    public void render(Map<String, ?> model, HttpServletRequest request, 
            HttpServletResponse response) throws Exception {
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.println("This is a custom view for BeanNameViewResolver <br />");
        writer.print("<b>Message- </b>" + model.get("msg"));
    }
}

ResourceBundleViewResolver Spring configuration

For ResourceBundleViewResolver bean “basename” property has the value views which means properties file is named views.properties file.

views.properties

msg.(class)=org.springframework.web.servlet.view.JstlView
msg.url=/WEB-INF/jsp/message.jsp

Here view URL is “/WEB-INF/jsp/message.jsp” so a JSP with the same name should be present at that location.

Corresponding handler method in the Controller class is as follows-

 @RequestMapping(value = "/showResource", method = RequestMethod.GET)
 public String showResource(Model model) throws Exception{
  model.addAttribute("msg", "Configuring ResourceBundleViewResolver example");
  return "msg";
 }

From the handler method, view name is returned as “msg” which is found in the views.properties file.

message.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC ResourceBundle view</title>
</head>
<body>
<h3>Spring MVC configuring multiple resolvers example</h3>
<b>Message</b> - <span>${msg}</span>
</body>
</html>

InternalResourceViewResolver Spring configuration

Another view resolver InternalResourceViewResolver is used to resolve the view name to JSPs.

Corresponding handler method in the Controller class is as follows-

 @RequestMapping(value = "/showUser", method = RequestMethod.GET)
 public String showUser(Model model) throws Exception{
  User user = new User("Leonard", "Nemoy", "ln@st.com");
  model.addAttribute("user", user);
  return "user";
 }

From the handler method, view name is returned as “user” which resolves to the JSP /WEB-INF/jsp/user.jsp

user.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC tutorial - User</title>
</head>
<body>
<table>
<tr>
<td><b>First Name</b> - <span>${user.firstName}</span></td>
</tr>
<tr>
<td><b>Last Name</b> - <span>${user.lastName}</span></td>
</tr>
<tr>
<td><b>Email</b> - <span>${user.email}</span></td>    
</tr>
</table>
</body>
</html>

Model class – User.java

public class User {

 private String firstName;
 private String lastName;
 private String email;

 public User() {
  
 }
 public User(String firstName, String lastName, String email) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.email = email;
 }
 
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
}

Spring MVC configuring multiple view resolvers – Controller class

Here is the full controller class.

@Controller
public class MultiViewController {
 @RequestMapping(value = "/showMsg", method = RequestMethod.GET)
 public String showMessage(Model model) throws Exception{
  model.addAttribute("msg", "Configuring multiple view resolver example");
  return "beanView";
 }
 
 @RequestMapping(value = "/showUser", method = RequestMethod.GET)
 public String showUser(Model model) throws Exception{
  User user = new User("Leonard", "Nemoy", "ln@st.com");
  model.addAttribute("user", user);
  return "user";
 }
 
 @RequestMapping(value = "/showResource", method = RequestMethod.GET)
 public String showResource(Model model) throws Exception{
  model.addAttribute("msg", "Configuring ResourceBundleViewResolver example");
  return "msg";
 }
}

Spring MVC configuring multiple view resolvers – Java configuration

If you are using Java configuration then same configuration as seen above using XML configuration can be written as following-

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.BeanNameViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="org.netjs.controller")
public class WebConfig implements WebMvcConfigurer {
 
 @Bean
 public ViewResolver viewResolver() {
  InternalResourceViewResolver resolver = new InternalResourceViewResolver();
  resolver.setPrefix("/WEB-INF/jsp/");
  resolver.setSuffix(".jsp");
  resolver.setOrder(3);
  return resolver;
 }
 @Bean
 public ViewResolver resourceResolver() {
  ResourceBundleViewResolver resourceResolver = new ResourceBundleViewResolver();
  resourceResolver.setBasename("views");
  resourceResolver.setOrder(2);
  return resourceResolver;
 }
 
 @Bean
 public ViewResolver beanViewResolver() {
  BeanNameViewResolver beanResolver = new BeanNameViewResolver();
  beanResolver.setOrder(1);
  return beanResolver;
 }
 @Bean("beanView")
 public View customView() {
  return new CustomView();
 }
 /**
  * Configure a handler to delegate unhandled requests by forwarding to the
  * Servlet container's "default" servlet. A common use case for this is when
  * the {@link DispatcherServlet} is mapped to "/" thus overriding the
  * Servlet container's default handling of static resources.
  */
 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
  configurer.enable();
 }
 
}

Setting order property for resolvers

Here note that the Resolvers have a property order set too which decides the priority. Lower order value means higher priority. Here BeanNameViewResolver has order property set as 0 which means Spring framework will first try to resolve view using this class.

As a rule InternalResourceViewResolver should always have higher order among all view resolvers value because it will always be resolved to view irrespective of value returned giving no chance to any other Resolver class.

Deploying and testing the application

Once the application is deployed to Tomcat server it can be accessed as shown below-

For BeanNameViewResolver (http://localhost:8080/spring-mvc/showMsg)

Spring MVC Configuring Multiple View Resolvers

For ResourceBundleViewResolver (http://localhost:8080/spring-mvc/showResource)

Configuring Multiple View Resolvers

For InternalResourceViewResolver (http://localhost:8080/spring-mvc/showUser)

Configuring Multiple View Resolvers in Spring MVC

That's all for this topic Spring MVC Configuring Multiple View Resolvers Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC PDF Generation Example
  2. Spring MVC Generate Response as JSON Example
  3. Spring MVC Form Example With Bean Validation
  4. Difference Between @Controller And @RestController Annotations in Spring
  5. Spring Batch Processing With List of Objects in batchUpdate() Method

You may also like -

  1. Select Query Using NamedParameterJDBCTemplate in Spring Framework
  2. Wiring Collections in Spring
  3. How to Inject Null And Empty String Values in Spring
  4. Bean Definition Inheritance in Spring
  5. Difference Between ArrayList And CopyOnWriteArrayList in Java
  6. Phaser in Java Concurrency
  7. Difference Between Encapsulation And Abstraction in Java
  8. Java Lambda Expression Comparator Example

Friday, 28 September 2018

Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block

Why wait(), notify() and notifyAll() methods in Java must be called inside a synchronized method or block is a very frequently asked Java multi-threading interview question. It is very closely related to another multi-threading question Why wait(), notify() and notifyAll() methods are in Object class?

There are few points we should be aware of before going into the reasons for why wait(), notify() and notifyAll() must be called inside a synchronized method or block.

  1. Every object created in Java has one associated monitor (mutually exclusive lock). Only one thread can own a monitor at any given time.
  2. For achieving synchronization in Java this monitor is used. When any thread enters a synchronized method/block it acquires the lock on the specified object. When any thread acquires a lock it is said to have entered the monitor. All other threads which need to execute the same shared piece of code (locked monitor) will be suspended until the thread which initially acquired the lock releases it.
  3. wait method tells the current thread (thread which is executing code inside a synchronized method or block) to give up monitor and go to waiting state.
  4. notify method wakes up a single thread that is waiting on this object's monitor.
  5. notifyAll method wakes up all the threads that called wait() on the same object.

Any method or a block of code, if not qualified with the keyword synchronized can be executed by more than one thread at any given time as object's monitor(lock) is not in the picture. Where as when a method is synchronized (or there is a synchronized block) only a single thread who has acquired the object's monitor can access the code.

I hope you would have got the picture by now. Since wait() method is about thread releasing the object's lock and go to sleep where as notify/notifyAll methods are about notifying the thread(s) waiting for the object's lock. So, wait(), notify() and notifyAll() methods (as mentioned above) should be invoked on an object only when the current thread has already acquired the lock on an object.
Infact not doing so will result in java.lang.IllegalMonitorStateException.

As example suppose I have this code where I have commented the synchronized keyword and trying to call wait

while(true){
    //synchronized (sharedListObj) {
    // While condition as mandated to avoid spurious wakeup
    while(sharedListObj.size() >= 1){
        try {
            sharedListObj.wait();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    // Putting value in the list
    System.out.println("Adding to queue - " + Thread.currentThread().getName() + " " + ++i);
    sharedListObj.add(i);
    //sharedListObj.notify();    
    // To get out of while(true) loop
    if(i > 4) break;
    //}
}

This will throw exception-

Exception in thread "Producer" java.lang.IllegalMonitorStateException
 at java.lang.Object.wait(Native Method)
 at java.lang.Object.wait(Object.java:502)
 at org.netjs.examples.Producer.run(InterThreadDemo.java:20)
 at java.lang.Thread.run(Thread.java:745)

To summarize it, wait() method tells the current thread (thread which is executing code inside a synchronized method or block) to give up monitor. Object's lock is acquired by a thread only when it is executing in a synchronized context. So it makes sense to use wait() method, which asks thread to release the lock, only in synchronized context.

Same way; when object's notify() or notifyAll() method is called, single thread (in case of notify) or all of the threads (in case of notifyAll), waiting for the object's lock change state to runnable and contend for the object's lock, and the thread that gets the lock starts execution. Here again, notify() and notifyAll() methods can inform other threads, that the object's lock can be acquired now, only if these methods are called from the synchronized object.

Recommendations for learning

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Spring Framework Master Class Course
  4. Complete Python Bootcamp Course
  5. Python for Data Science and Machine Learning

So these are the reasons Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block. Please do share with me if you know any other reason for doing the same.


Related Topics

  1. Thread Priorities in Java Multi-Threading
  2. Can we Start The Same Thread Twice in Java
  3. Volatile in Java
  4. String And Thread-Safety in Java
  5. Java Multi-Threading Interview Questions

You may also like -

  1. Externalizable interface in Java
  2. covariant return type in Java
  3. interface default methods in Java 8
  4. Lambda expression examples in Java 8
  5. How HashMap internally works in Java
  6. Overriding hashCode() and equals() method in Java
  7. Difference Between Checked & Unchecked Exception in Java
  8. Batch Processing in Java-JDBC

How to Remove Elements From an Array - Java Program

Writing a Java program to remove element from an array may look like a simple task but it comes with its own set of problems. Those problems stem from the fact that array in Java is fixed in length. Which means you can't just remove an element from the given index in an array, you will need to shift all the elements, that are after the element that has to be removed, to the left to fill the gap left by the removed element.

Once the element are shifted to fill the gap, that leaves space at the end of the array (remember array size is fixed). Array size will not reduce after removing the element and the element that is at the end will be repeated to fill the empty space.

Let's try to clarify it with an example -

Here the array removal is done without using any third party tool (like Apache common utils) or any data structure provided by the Java language (Like Collection classes).

So the steps followed to remove element from an array are-

  1. Ask the user to enter the element to be removed.
  2. Search in the array for the given element.
  3. If found shift all the element after that index to the left by one element. As example if element to be deleted is at index i then remove all the elements from index i+1 to array.length by one element which means element at i+1 will come at index i.

Java program to remove element from an array

 
import java.util.Scanner;

public class ElemRemoval {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] intArr = {1, 2, 5, 12, 7, 3, 8};
        System.out.print("Enter Element to be deleted : ");
        int elem = in.nextInt();
        
        for(int i = 0; i < intArr.length; i++){
            if(intArr[i] == elem){
                // shifting elements
                for(int j = i; j < intArr.length - 1; j++){
                    intArr[j] = intArr[j+1];
                }
                break;
            }
        }
      
        System.out.println("Elements -- " );
        for(int i = 0; i < intArr.length; i++){
            System.out.print(" " + intArr[i]);
        }                
    }
}

Output

Enter Element to be deleted : 5
Elements -- 
 1 2 12 7 3 8 8

If you notice last element 8 is repeated to fill the space that is left after shifting the elements.

Now when you have the basic idea about the scenarios that you need to take care of while removing element from an array. let's see what all alternatives are there to do that.


Using new array

When you remove an element from an array, you can fill the empty space with 0, space or null depending on whether it is a primitive array, string array or an Object array.

Other alternative is to create a new array and copy the elements in that array. New array should have size of old array’s size – 1.

Let’s see an example where new array is used -

 
import java.util.Scanner;

public class ElemRemoval {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] intArr = {1, 2, 5, 12, 7, 3, 8};
        int[] newArr = null;
        System.out.print("Enter Element to be deleted : ");
          int elem = in.nextInt();
        
        /*for(int i = 0; i < intArr.length; i++){
            if(intArr[i] == elem){
                
                for(int j = i; j < intArr.length - 1; j++){
                    intArr[j] = intArr[j+1];
                }
                break;
            }
        }*/
        
         for(int i = 0; i < intArr.length; i++){
             if(intArr[i] == elem){
                newArr = new int[intArr.length - 1];
                for(int index = 0; index < i; index++){
                    newArr[index] = intArr[index];
                }
                for(int j = i; j < intArr.length - 1; j++){
                    newArr[j] = intArr[j+1];
                }
                break;
             }
         }
         System.out.println("Elements -- " );      
         for(int i = 0; i < newArr.length; i++){
             System.out.print(" " + newArr[i]);
         }                
    }
}

Output

Enter Element to be deleted : 
5
Elements -- 
 1 2 12 7 3 8

Enter Element to be deleted : 8
Elements -- 
 1 2 5 12 7 3

With copying the element to the new array problem of empty space is solved.

Using ArrayUtils to remove element from an array

If you can use Apache commons in your application then there is a utility class ArrayUtils that can be used to remove elements from an array.

 
import java.util.Scanner;
import org.apache.commons.lang3.ArrayUtils;

public class ElemRemoval {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] intArr = {1, 2, 5, 12, 7, 3, 8};
        System.out.print("Enter Element to be deleted : ");
            int elem = in.nextInt();
            for(int i = 0; i < intArr.length; i++){
              if(intArr[i] == elem){
                // Using ArrayUtils
                intArr = ArrayUtils.remove(intArr, i);
                break;
              }
          }
        
          System.out.println("Elements -- " );
          for(int i = 0; i < intArr.length; i++){
              System.out.print(" " + intArr[i]);
          }
    }
}

Output

Enter Element to be deleted : 2
Elements -- 
 1 5 12 7 3 8

Using System.arraycopy() method to remove element from an array

Description of the System.arraycopy method

System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) - Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array.

If you use the same array as source and destination you will have the same issue of repeating element as discussed in the first program as the array length is fixed. In the example code new array is used as destination.

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

public class ElemRemoval {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] intArr = {1, 2, 5, 12, 7, 3, 8};
        
        
        System.out.print("Enter Element to be deleted : ");
          int elem = in.nextInt();
          for(int i = 0; i < intArr.length; i++){
              if(intArr[i] == elem){
                removeElement(intArr, i);
                break;
              }
          }       
    }
    
    public static void removeElement( int [] arr, int index ){
        // Destination array
        int[] arrOut = new int[arr.length - 1];
        int remainingElements = arr.length - ( index + 1 );
        // copying elements that come before the index that has to be removed
        System.arraycopy(arr, 0, arrOut, 0, index);
        // copying elements that come after the index that has to be removed
        System.arraycopy(arr, index + 1, arrOut, index, remainingElements);
        System.out.println("Elements -- "  + Arrays.toString(arrOut));
    }
}

Output

Enter Element to be deleted : 5
Elements -- [1, 2, 12, 7, 3, 8]

Using ArrayList to remove element from an array

If you want to remove element from an array using Collection API provided by the Java language then you can convert array to an ArrayList and then remove element from the ArrayList. Shuffling and all would be taken care of by the ArrayList itself. Once the element is removed you can again convert the ArrayList to an array.

 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class ElemRemoval {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Integer[] intArr = {1, 2, 5, 12, 7, 3, 8};            
        System.out.print("Enter Element to be deleted : ");
          int elem = in.nextInt();
        
          System.out.println("Original Array " + Arrays.toString(intArr));
        
          for(int i = 0; i < intArr.length; i++){
              if(intArr[i] == elem){
                intArr = removeElementUsingCollection(intArr, i);
                break;
              }
          }
          System.out.println("Array after removal of Element -- " );
          for(int i = 0; i < intArr.length; i++){
              System.out.print(" " + intArr[i]);
          }
        
    public static Integer[] removeElementUsingCollection( Integer[] arr, int index ){
        List<Integer> tempList = new ArrayList<Integer>(Arrays.asList(arr));
        tempList.remove(index);
        return tempList.toArray(new Integer[0]);
    }
}

Output

Enter Element to be deleted : 2
Original Array [1, 2, 5, 12, 7, 3, 8]
Array after removal of Element -- 
 1 5 12 7 3 8

Recommendations for learning

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Complete Python Bootcamp Course
  4. Java: The Complete Reference
  5. Effective Java 3rd Edition

That's all for this topic How to Remove Elements From an Array - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Finding duplicate elements in an array - Java Program
  2. Remove Duplicate Elements From an Array in Java
  3. Matrix Subtraction - Java Program
  4. Difference between Array and ArrayList in Java
  5. How ArrayList works internally in Java

You may also like -

  1. Splitting a String - Java Program
  2. How to format date in Java using SimpleDateFormat
  3. How to create PDF from XML using Apache FOP
  4. How to create deadlock in Java multi-threading - Java Program
  5. Difference between equals() method and equality operator == in Java
  6. Arithmetic and Unary Operators in Java
  7. Object cloning in java
  8. Nested class and Inner class in Java

Exception Propagation in Java Exception Handling

This post shows what is exception propagation in Java and how does exception propagate in case of checked and unchecked exceptions in Java

Exception propagation

When an exceptional condition occurs within a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred.

The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception. This process of going through the method stack is known as Exception propagation in Java.

Note that, if your program is not able to catch any particular exception, that will ultimately be processed by the default handler.

Exception propagation Java example with unchecked Exception

In this example code there are three methods method1, method2 and method3. From method1, method2 is called which in turn calls method3. In method3 there is an operation which will result in an exception. You can see how exception propagates all the way to method1 where it is eventually caught.

public class ExceptionPropagation {

 public static void main(String[] args) {
  ExceptionPropagation exObj = new ExceptionPropagation();
  exObj.method1();
  System.out.println("After handling exception...");
 }
 
 void method3(){
  System.out.println("In method3");
  // This will result in Arithmetic Exception
  // as an attempt is made to divide by zero
  int result = 7/0;  
 }
 
 // This method will forward the exception
 void method2(){
  System.out.println("In method2");
  method3();
 }
 
 // Exception will be handled here
 void method1(){
  try{
   method2();
  } catch(Exception e){
   System.out.println("Exception caught");
  }
 }
}

Output

In method2
In method3
Exception caught
After handling exception
exception propagation in Java
Searching the stack for appropriate Exception Handler

Exception propagation in Java with checked exception

In case of checked exception compiler forces you to put try-catch block so exception has to be handled where it is thrown. If you don't want to do that then you have to declare it in throws clause. Then exception will propagate to the calling method and it should be caught there or it should be declared in throws clause of that method signature too.

public class ExceptionPropagation {

 public static void main(String[] args) {
  ExceptionPropagation exObj = new ExceptionPropagation();
  exObj.method1();
  System.out.println("After handling exception");
 }
 
 // This method declares the exception in throws clause
 void method3() throws FileNotFoundException{
  System.out.println("In method3");
  // throwing exception
  throw new FileNotFoundException();  
 }
 
 // This method also declares the exception in throws clause
 void method2() throws FileNotFoundException{
  System.out.println("In method2");
  method3();
 }
 
 // Exception will be handled here
 void method1(){
  try{
   method2();
  } catch(FileNotFoundException ex){
   System.out.println("FileNotFoundException caught");
  }
 }
}

That's all for this topic Exception Propagation in Java Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. finally Block in Java Exception Handling
  2. Difference Between throw And throws in Java Exception Handling
  3. Try-With-Resources in Java Exception Handling
  4. Best Practices For Exception Handling in Java
  5. Java Exception Handling Interview Questions And Answers

You may also like -

  1. finalize method in Java
  2. Automatic numeric type promotion in Java
  3. Abstraction in Java
  4. Why file name and class name should be same in Java
  5. Lambda expressions in Java 8
  6. Count Number of Words in a String - Java Program
  7. How to create PDF from XML using Apache FOP
  8. Difference Between sleep And wait in Java Multi-Threading

Thursday, 27 September 2018

finalize Method in Java

In Java when there are no more references to the object that object is eligible to be garbage collected. There may be a situation where an object needs to perform some action just before it is getting garbage collected. For example if an object is holding some non-java resources like file handle then it is better to make sure that these resources are closed before an object is garbage collected because simply reclaiming the memory used by an object would not guarantee that the resources it held would be released. For that purpose Java provides a mechanism called finalization through finalize() method. finalize method in Java is called by the garbage collector on an object for cleaning up resources just befor the object is garbage collected.

General form of Java finalize() method

finalize method in Java is provided as a protected method in the Object class.

protected void finalize() throws Throwable

Just as a reminder the protected access modifier means - Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

Since all the classes have Object class as the super class either directly or indirectly so this method would be accessible to each and every class anyway so it makes sense to keep the access as protected.

When is finalize() method called in Java

As we know that in Java object memory deallocation happens automatically through garbage collection. In Java, garbage collector is run by the run time environment periodically and it looks for the objects for which there are no existing references. finalize method for an object is executed just before it is garbage collected. But here lies the caveat According to Java language specification - http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.6 The Java programming language does not specify how soon a finalizer will be invoked that's one reason why we should not rely solely on finalize() method to release resources.

According to Joshua Bloch in his book Effective Java, Item 7: Avoid Finalizers
"The promptness with which finalizers are executed is primarily a function of the garbage collection algorithm, which varies widely from JVM implementation to JVM implementation. The behavior of a program that depends on the promptness of finalizer execution may likewise vary. It is entirely possible that such a program will run perfectly on the JVM on which you test it and then fail miserably on the JVM favored by your most important customer."

Note that finalize method is deprecated from Java 9 onwards. Reference- https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#finalize()

How to use finalize method in Java

The finalize method provided by root class Object performs no special action; it simply returns normally. Any class which needs some functionality to be provided in finalize() method has to override this definition and provide the functionality for cleanup.

According to Java docs- The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded.

Java example for finalize() method

Here is a simple example where an object is created then that object reference is set as null. Also, System.gc() is called explicitly to run garbage collector. That should mean a call to finalize() method before the object is garbage collected. Note you may not get the output in some of the runs as System.gc() is more of a suggestion to the Java virtual machine to reclaim memory from unused objects, it may not run as soon as System.gc() is called and the program may terminate without calling the finalize method.

public class FinalizeDemo {
    int i;
    FinalizeDemo(int num){
        this.i = num;
    }
    public static void main(String[] args) {
        // creating object
        FinalizeDemo finalizeDemo = new FinalizeDemo(10);
        Temp temp = new Temp();
        // setting object reference as null so it is 
        // eligible for garabge collection
        finalizeDemo = null;
        temp.doCalcualtion();
        // setting object reference as null so it is 
        // eligible for garabge collection
        temp = null;
        // Calling System.gc() to run garbage collector
        System.gc();        
    }
    
    @Override
    protected void finalize() throws Throwable {
        try{
            System.out.println("finalize method called for FinalizeDemo");
        }finally{        
            super.finalize();
        }
    } 
}

class Temp{    
    public void doCalcualtion(){
        int i = 5;
        System.out.println("value of i is " + i);
    }
    @Override
    protected void finalize() throws Throwable {
        try{
            System.out.println("finalize method called for Temp");
        }finally{
            super.finalize();
        }
    }
}

Output

value of i is 5
finalize method called for Temp
finalize method called for FinalizeDemo

Though I have used System.gc here to some how make sure that finalize() method is indeed called but don't rely on it. To quote Joshua Bloch again "Don't be seduced by the methods System.gc and System.runFinalization. They may increase the odds of finalizers getting executed, but they don't guarantee it. The only methods that claim to guarantee finalization are System.runFinalizersOnExit and its evil twin, Runtime.runFinalizersOnExit. These methods are fatally flawed and have been deprecated."

How to properly write a finalize() method in Java

Like constructor chaining in Java there is no finalizer chaining so super class finalize method would not be called automatically.

As example- If there is a parent class A which provides a finalize method and child class B that extends class A and overrides finalize method. Then only Class B's finalize method will be called. Parent Class A's finalize method would not be called automatically. It has to be explicitly called using super. In that case class B's finalize method will look like-

protected void finalize() throws Throwable {
     try {
         // clean up
     } finally {
         super.finalize(); // call parent class’ finalize
     }
}

When can you use finalize method

Though there are other better alternatives to clean up resources like a finally block or try-with-resources(ARM) available from Java 7. But to make sure, just as an extra safety measure, that resources are indeed closed before the object is destroyed finalize() method may be used. But be forewarned it comes with a hit on performance.

Finalize method and exception handling

Any exception thrown by the finalize method while finalize method is executing causes the finalization of this object to be halted, but is otherwise ignored.

Points to Note

  1. Every class in Java inherits the finalize() method from java.lang.Object.
  2. finalize method in Java is called by the garbage collector when it determines no more references to the object exist.
  3. The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.
  4. If overridding finalize() method, it is a good programming practice to use a try-catch-finally statement and to always call super.finalize() as there is no concept of finalizer chaining.
  5. The finalize method is never invoked more than once by a Java virtual machine for any given object.
  6. finalize method is deperecated from Java 9.

That's all for this topic finalize Method in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. final Vs finally Vs finalize in Java
  2. Constructor chaining in Java
  3. Association, Aggregation And Composition in Java
  4. super in Java
  5. Core Java Basics Interview Questions

You may also like -

  1. strictfp in Java
  2. Multi catch statement in Java 7
  3. interface static methods in Java 8
  4. Overriding hashCode() and equals() method in Java
  5. fail-fast Vs fail-safe iterator in Java
  6. Splitting a String - Java Program
  7. What if run() method called directly instead of start() method
  8. Difference between Thread and Process in Java