See the Tutorial List

Java Thread Class

Thread class is the main class on which Java's Multithreading system is based. Thread class, along with its companion interface Runnable will be used to create and run threads for utilizing Multithreading feature of Java.


Constructors of Thread class

  1. Thread()
  2. Thread(String str)
  3. Thread(Runnable r)
  4. Thread(Runnable r, String str)

You can create new thread, either by extending Thread class or by implementing Runnable interface. Thread class also defines many methods for managing threads. Some of them are,


MethodDescription
setName()to give thread a name
getName()return thread's name
getPriority()return thread's priority
isAlive()checks if thread is still running or not
join()Wait for a thread to end
run()Entry point for a thread
sleep()suspend thread for a specified time
start()start a thread by calling run() method

Some Important points to Remember

  1. When we extend Thread class, we cannot override setName() and getName() functions, because they are declared final in Thread class.
  2. While using sleep(), always handle the exception it throws.
    static void sleep(long milliseconds) throws InterruptedException

Shutdown hook

In Java, Shutdown hook is used to clean-up all the resource, it means closing all the files, sending alerts etc.. We can also save the state when the JVM shuts down. Shutdown hook mostly used when any code is to be executed before any JVM shuts down. Following are some of the reasons when the JVM shut down:

  • Pressing ctrl+c on the command prompt
  • When the System.exit(int) method is invoked.
  • When user logoff or shutdown etc

addShutdownHook(Thread hook)

The addShutdownHook(Thread hook) method is used to register the thread with the virtual machine. This method is of Runtime class.

Example:

	
class Demo6 extends Thread
{  
    public void run()
	{  
	System.out.println("Shutdown hook task is Now completed...");  
	}  
}  

public class ShutdownDemo1
{  
	public static void main(String[] args)throws Exception 
	{  

		Runtime obj=Runtime.getRuntime();  
		obj.addShutdownHook(new Demo6());  
		System.out.println("Now main method is sleeping... For Exit press ctrl+c");  
		try
		{
			Thread.sleep(4000);
		}
		catch (Exception e) {}  
	}  
}  
	

shutdown_hook

OutOfMemory Exception

In Java, as we know that all objects are stored in the heap. The objects are created using the new keyword. The OutOfMemoryError occurs as follow:

out-of-memory-exception

This error occurs when Java Virtual Machine is not able to allocate the object because it is out of memory and no memory can be available by the garbage collector.

The meaning of OutOfMemoryError is that something wrong is in the program. Many times the problem can be out of control when the third party library caches strings.

Basic program in which OutOfMemoryError can occur

Example:

	
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class OutOfMemoryDemo1 {
	public static void main(String[] args) {
		Listobj = new ArrayList<>();
		Random obj1= new Random();
		while (true)
			obj.add(obj1.nextInt());
	}
}
	

out-of-memory-exception-example

Program in which OutOfMemoryError can occur because of low memory

Example:

	
public class OutOfMemoryErrorDemo2
{
	public static void main(String[] args) 
	{
		Integer[] a = new Integer[100000*10000*1000];
		System.out.println("Done");
	}
}
	

out-of-memory-exception-example-2.JPG

Program in which OutOfMemoryError can occur, when Garbage Collector exceed the limit

Example:

	
import java.util.*; 

public class OutOfMemoryErrorDemo2{ 
public static void main(String args[]) throws Exception 
    { 
        Map a = new HashMap(); 
        a = System.getProperties(); 
        Random b = new Random(); 
        while (true) { 
a.put(b.nextInt(), "randomValue"); 
        }   } 
}
	

out-of-memory-exception-example