Tag Archives: finalize () method

Java: final Vs finally Vs finalize


Here is a list of key differences between final, finally and finalize:

final

  • final is keyword
  • final is use with class, method, and variables
  • A final class can not be instantiated.
  • A final method can not be overridden.
  • A final variable can not be re-assigned.

final Example

A final variable can not be re-assigned.

final variable example
Final Variable can be reassigned

A final class can not be subclassed.

Final Class Example
Final class can not be subclassed

A final method can not be overridden.

Final method Example
final method can not be overloaded

finally

  • finally is keyword
  • finally block is used in exception handling that follows try block.
  • finally block of code always executes, whether an exception occurred or not. It’s used to run clean-type resources.
  • After java 7+ by using try-resources with files make finally as optional.

finally Example

In this example, you will see finally block executes, whether an exception occurred or not.

public class TesFinally {
   public static void main(String[] args) {

      try{
         int a = 20;
         int b = 0;
         int result = a/b;
      }catch(Exception e){
         System.out.println("Exception occured: "+ e.getMessage());
      }
      finally{
         System.out.println("Finally Exceuted.");
      }
   }
}

Output


Exception occured: / by zero
Finally Executed.

finalize

  • finalize is an object class method
  • finalize() method is called just before the object is destroyed or garbage collected.
  • finalize() method is used to clean up object resources before destroy.
  • If finalize() method call Explicitly, then it will be executed just like a normal method but the object won’t be deleted/destroyed.

See Also: Java: Garbage Collection Finalize() Method Example And Uses

finalize Example

In this example first calling finalize() method manually by test object which will behave as a normal method. For checking how Garbage collector call finalize() method setting test as null make object as unreferenced to make eligible for garbage collection. Here calling System.gc() to request JVM to call the garbage collector method. Now it’s up to JVM to call Garbage Collector or not. Usually, JVM calls Garbage Collector when there is not enough space available in the Heap area or when the memory is low.

public class FinalizeMethodTest {

    public static void main(String[] args) {
        FinalizeMethodTest test=new FinalizeMethodTest();
        //manually calling finalize method is call like normal method
        test.finalize();

        //unreferenced object to make eligible for garbage collector
        test=null;

        //Requesting JVM to call Garbage Collector method
        System.gc();

        System.out.println("Main Method Completed !!");
    }
    @Override
     public void finalize()
        {
            System.out.println("finalize method overriden");
        }
}

Output


finalize method overriden
Main Method Completed !!
finalize method overriden

Here finalize() method calls two times one for manually another by garbage collector for cleaning up this test object.

 

Java : java.lang.Object Class & Methods


java.lang.Object  is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. It’s also called as Object Class.

Methods of Object Class

Below are methods of Object Class for different purpose  as below:

  1. protected Object clone() : Creates and return copy of this object.
  2. boolean equals(Object obj) : Indicate weather other object is equal or not.
  3. protected void finalize() : To make object finalize for garbage collection.
  4. Class getClass() : Returns the runtime class of this Object.
  5. int hashCode() : Returns a hash code value of Object.
  6. void notify() : Wakes up a single thread that is waiting on this object’s monitor. It works in multithread env with tow thread only.
  7. void notifyAll() : Wakes up all threads that are waiting on this object’s monitor. if more than one thread running.
  8. String toString() : Returns string representation of object.
  9. void wait() : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
  10. void wait(long timeout) : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. or specified time has elapsed.
  11. void wait(long timeout, int nanos) : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

In this below examples you can see how to override and utilize these methods in different ways.

Example of clone() method

Object class clone() method, create and return copy of a object(). For implementing a clone method class have implements Cloneable interface which is a Marker Interface. There are two ways of cloning of object Shallow Cloning and Deep Cloning. For more detail follow below link.

Java : Shallow and Deep Object Cloning

Eample of finalize() method

Garbage collector calls Object class finalize() method before clean object. We can override this method for code clean-up activity like closing files, database connection and socket. Follow below link to know more about finalize() method example and uses:

Java : Garbage Collection finalize() method example and uses

Example of hashCode(), equals() and toString() method

Override toString() method to print object values. Same way we can override hash() code and equals() method also. hashcode and equals() method have contract as:

“If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. If you only override equals() and not hashCode() your class violates this contract

For example of toString(), hashcode() and equals() follow below link:

Java : How to remove duplicate objects from list?

Example of getClass() method

The getClass() method returns the run time class of an object.  As in below examples returning class name of objects.

import java.util.Calendar;

public class GetClassExample {

	public static void main(String[] args) {
		GetClassExample test=new GetClassExample();

		System.out.println("Class Name :"+test.getClass().getName());

		Calendar calendar=Calendar.getInstance();
		System.out.println("Calendar Class Name :"+calendar.getClass().getName());

		Integer integer=new Integer(10);
		System.out.println("Integer Class Name :"+integer.getClass().getName());

	}
}

Output


Class Name :com.Object.GetClassExample
Calendar Class Name :java.util.GregorianCalendar
Integer Class Name :java.lang.Integer

Example of wait(), notify() and notifyAll() method

Below is example of restaurant using method wait(), notify() and notifyAll(). Where Two waiter thread are running and waiting for  order message when they got order notify will pass the order message and based on available waiter will process order.

public class Order {
    private String msg;
    public Order(String msg){
        this.msg=msg;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String str) {
        this.msg=str;
    }
}

Waiter class that will wait for other threads to invoke notify methods to complete it’s processing. Notice that Waiter thread is owning monitor on Order object using synchronized block.

public class Waiter implements Runnable{
    private Order msg;
    public Waiter(Order msg){
        this.msg=msg;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        synchronized (msg) {
            try{
                System.out.println(name+" waiting to get notification at time:"+System.currentTimeMillis());
                msg.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(name+" waiter thread got notification at time:"+System.currentTimeMillis());
            //process the order now
            System.out.println(name+" processed: "+msg.getMsg());
        }
    }
}

Here notification thread will call notify() method on order message so that available waiter will pick the order.Notice that synchronized block is used to own the monitor of Order object.

public class Notification implements Runnable {
    private Order msg;
    public Notification(Order msg) {
        this.msg = msg;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name+" started");
        try {
            Thread.sleep(1000);
            synchronized (msg) {
                msg.setMsg(name+" Notification work done");
                msg.notify();
                //use notify all when lots of thread are running
                // msg.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Below test class having multiple threads of Waiter and notification to execute order.

public class WaitNotifyExample {
	public static void main(String[] args) {
		Order order= new Order("My Order");
	        Waiter waiter1 = new Waiter(order);
	        new Thread(waiter1,"waiter 1").start();

	        Waiter waiter2 = new Waiter(order);
	        new Thread(waiter2, "waiter 2").start();

	        Notification notification = new Notification(msg);
	        new Thread(notification, "notification").start();
	        System.out.println("All the threads are started");
	}
}

When we will execute the above program, we will see below output but program will not complete because there are two waiter threads waiting for Order object and notify() method has wake up only one of them, the other waiter thread is still waiting to get notified.

Output


waiter 2 waiting to get notification at time:1552127934935
waiter 1 waiting to get notification at time:1552127934935
notification started
All the threads are started
waiter 2 waiter thread got notification at time:1552127935946
waiter 2 processed: notification Notification work done

or


waiter 1 waiting to get notification at time:1552127972873
All the threads are started
notification started
waiter 2 waiting to get notification at time:1552127972873
waiter 1 waiter thread got notification at time:1552127973876
waiter 1 processed: notification Notification work done

Conclusion

Here you learn about the Object class and it’s methods. How to use these objects class methods with example and where can we use that.

References

https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html

Java : Garbage Collection finalize() method example and uses


finalize() is an Object class method that is called by Garbage Collector just before deleting/destroying the object which is eligible for garbage collection before clean-up activity. Clean-up activity means closing the resources associated with that object like Database Connection, Network Connection or we can say resource de-allocation.

Points to Remember:

  • finalize() is a method not reserved keyword.
  • If finalize() method call manually by object instance then it will treat as normal method;
  • Once finalize() method completes immediately Garbage Collector destroy that object.
  • There is no guarantee about the time when finalizing () method is called. It may be called any time after the object is not being referred anywhere (can be garbage collected).

Syntax  of finalize() method:


protected void finalize throws Throwable{}

Since Object is the superclass of all the classes and finalize() is the Object class method hence finalize() method is available for every java class hence Garbage Collector can call finalize method on any java object. We also override this finalize() method for code clean-up activities.

finalize() method Example

In this example first calling finalize() method manually by test object which will behave as a normal method. For checking how Garbage collector call finalize() method setting test as null make object as unreferenced to make eligible for garbage collection. Here calling System.gc() to request JVM to call the garbage collector method. Now it’s up to JVM to call Garbage Collector or not. Usually, JVM calls Garbage Collector when there is not enough space available in the Heap area or when the memory is low.

public class FinalizeMethodTest {

	public static void main(String[] args) {
		FinalizeMethodTest test=new FinalizeMethodTest();
		//manually calling finalize method is call like normal method
		test.finalize();

		//unreferenced object to make eligible for garbage collector
		test=null;

		//Requesting JVM to call Garbage Collector method
		System.gc();

		System.out.println("Main Method Completed !!");
	}
	@Override
	 public void finalize()
	    {
	        System.out.println("finalize method overriden");
	    }
}

Output


finalize method overriden
Main Method Completed !!
finalize method overriden

Here finalize() method calls two times one for manually another by garbage collector for cleaning up this test object.

Exception Handling in finalize() method

If any exception happens in the finalize method then if we calling finalize manually then we have to handle it otherwise program will terminate abnormally. If finalize() method called by Garbage collector and then any unchecked exception happen then JVM will take care of it and the program will not terminate.

public class FinalizeMethodTest {

public static void main(String[] args) {
FinalizeMethodTest test=new FinalizeMethodTest();
//manually calling finalize method is call like normal method
try
{
test.finalize();
}
catch(Exception ex)
{
ex.printStackTrace();
}

//unreferenced object to make eligible for garbage collector
test=null;

//Requesting JVM to call Garbage Collector method
System.gc();

System.out.println("Main Method Completed !!");
}
@Override
public void finalize()
{
System.out.println("finalize method overriden");
//Exception occured here
System.out.println(10 / 0);
}<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
}

Output


finalize method overriden
java.lang.ArithmeticException: / by zero
    at classes.ObjectClass.FinalizeMethodTest.finalize(FinalizeMethodTest.java:30)
    at classes.ObjectClass.FinalizeMethodTest.main(FinalizeMethodTest.java:10)
Main Method Completed !!
finalize method overriden

In this example, we have to handle exception explicitly while calling finalize() method manually while calling by Garbage Collector no exception thrown.

Conclusion

In this blog, we learn about finalize() method calling manually and by Garbage Collector. Also, see by example to handle exception for both cases.