Skip to main content


Showing posts from February, 2021

Can we Override start() Method in Java

In some Java interviews there is a question asked can we override start() method in Java . Since this is something you will hardly need to do, so some people do hesitate that is it actually possible to override start() method of Thread class or not. Also there is a follow up question will your overridden start() method actually execute the thread and call the run() method or not. Overriding start method in Java Yes it is possible to override start() method of the Thread class in Java. Though it is hardly required to do that except for some rare scenarios where you do need some logic to be executed before calling the run() method. From your overridden start() method ensure that you call super.start() method as Thread class’ start() method is a native method and has the logic to communicate with the OS to schedule the thread to run . Failing to call super.start() will mean run() method won’t be called. Overriding start method example code public class MyThread extends Thread

Can we Start a Thread Twice in Java

Can we start a thread twice in Java is a frequently asked Java interview question. The short answer is no and this post tries to explain why it is not possible to call start() method twice on the same thread in Java. Thread is terminated after run() method As explained in the post Life Cycle of a Thread (Thread States) in Java once the thread finishes executing its run() method, it goes to terminated state (i.e. thread is dead). Since the thread object is already dead so calling start() method on the thread is not permitted and an exception is thrown. As per the Java docs - It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution. Throws: IllegalThreadStateException - if the thread was already started. Reference : Thus a Thread can only be started once, trying to start the same thread again in Java will throw Ille

Thread Group in Java

All threads belong to one of a thread group in Java. When you create a thread in Java it is put into a thread group specified either by you or to the same group as the thread that created it if no thread group is explicitly specified. Table of contents Default thread group Usage of thread group in Java ThreadGroup Class in Java Creating Thread in specific thread group Thread group Java example Default thread group When a Java application is started one thread starts running immediately which is known as main thread in Java and this main thread belongs to a thread group called main . If you create other threads (with in the context of main thread) with out specifying thread group then these thread will also belong to main thread group. Usage of thread group in Java Thread groups provide a convenient way to manage multiple threads as a single thread group object. Using that thread group object you can manipulate all the threads belonging to that group as a

Thread Priority in Java With Examples

In a multi-threaded environment, the order in which threads will get CPU cycle is decided by the thread scheduler and it uses thread priority to decide that order. Though that doesn’t mean that the low priority threads will never get a chance to run, that is thread priority in Java won’t lead to a deadlock but low priority threads will get fewer CPU cycles. Higher priority thread can also preempt a lower-priority thread. Java thread priority Every thread in Java has a priority assigned to it. When you create a thread in Java it inherits the priority of the thread that created it. You can change thread’s priority at any time after its creation using the setPriority() method of the Thread class. If you want to check the thread’s priority you can check it using getPriority() method of the Thread class. setPriority(int newPriority) - Changes the priority of this thread. Here newPriority is the priority to set this thread to. If the priority is not in the range MIN_PRIORITY

Daemon Thread in Java

Daemon thread in Java is a thread that runs in background to perform some tasks for the program as long as the program is running. Even if daemon threads are running that doesn’t prevent JVM from shutting down. Features of daemon thread in Java 1. The Java Virtual Machine exits when the only threads running are all daemon threads. So, the JVM waits only for the non-demon threads in a program to complete. That is why daemon threads in Java are suitable for performing general tasks like clearing the in-memory cache which may be essential to a program but not the main part of the program. Even the JVM, when it starts, creates daemon threads for garbage collection and other book keeping tasks and a non-daemon main thread for executing the program. That is also the reason why JVM doesn’t wait for daemon threads to finish as daemon thread in Java is supposed to perform some background tasks for the user threads. If user threads have completed there is no sense in executing the dae

Main Thread in Java

Java is one of the first programming language to provide built-in support for multi-threading. In fact when a Java program starts one thread starts running immediately that thread is known as main thread in Java . If you ever tried to run a Java program with compilation errors you would have seen the mentioning of main thread. Here is a simple Java program that tries to call the non-existent getValue() method. public class TestThread { public static void main(String[] args) { TestThread t = new TestThread(); t.getValue(); } } Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method getValue() is undefined for the type TestThread As you can see in the error when the program is executed, main thread starts running and that has encountered a compilation problem. Java Main Thread Main thread in Java is important as your Java program will start running on this thread. Additional threads spawned in your program will inherit s

How to Create And Start Thread in Java

In order to create a thread in Java you need to get an instance of java.lang.Thread class. You can do it in two ways. By implementing Runnable interface. By Extending Thread class. Whichever of these two ways is chosen by you to create a thread in Java you need to override run() method and provide the code that will run in that thread . Thread’s run() method will be executed once you call start() method on the created thread. Creating and starting thread in Java involves the following steps. Get an instance of the Thread class. Call start method on the created thread object-  thread.start(); Once the thread is started run method will be executed. Creating thread by implementing Runnable interface One of the ways to create a thread in Java is to implement the Runnable interface. Runnable interface is a functional interface in Java with a single method run() which has to be implemented. @FunctionalInterface public interface Runnable { public abstr

Multithreading in Java Tutorial

You would have seen a lot of examples of multi-tasking where computer programs are handling more than one task at a time. For example- You can start a player and play songs while working on any editor and have a document of 100 pages getting printed at the same time. This is an example where separate processes are running concurrently . Same way with in the same program you can have several tasks running like in a song player you can start playing a song and at the same time click on "add song" button to add more songs to your playlist. With in a program these separate running tasks are called threads and this concept of dividing a program into separate sub-tasks to make it faster and more responsive is called multi-threading . Multithreading in Java Java is one of the first programming language to provide in-built support for multi-threading programming. In Java multithreading the main class is Thread class , any thread in Java is an object of Thread class and th

How to Create Thread in Python

In Python threading module has a Thread class which is used for creating thread. There are two ways to create a new Thread in Python. By creating Thread instance and passing the function that has to be executed as one of the argument to the constructor of the Thread. By creating a class that extends Thread class and overrides run method. 1. Python thread creation using threading.Thread() constructor In Python you don’t have to always create classes. You can just create a Python file with functions for some scripting purposes. In such scenario if you want to take advantage of multi-threading, threading.Thread() is the way to go (Though you can use it with classes too). You need to pass the function that has to be executed as one of the argument to the constructor of the Thread. Full constructor call with all the arguments is as given below- threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None) This constructor should al

Python Multi-threading Tutorial

In this tutorial we’ll see the support for multi-threading in Python. Table of contents What is multi-tasking Multi-threading in Python Python thread creation example Python Thread class methods Main thread in Python What is multi-tasking In concurrent programming there are two types of multitasking- Process based multitasking Thread based multitasking Process based multitasking We run a lot of processes simultaneously on our computer for example working on a word document while playing songs and also having some sites opened in a browser. This is an example of running separate processes concurrently. Here just to clarify it, with a single processor only a single process is executed by a processor at any given time. Processor divides its execution time between different processes and executes them for the given time slice, that’s why term "time slicing" is also used. For example if there are three processes loaded into memory and a

How to Unzip a File in Java

When you zip a file in Java there are different logic based on whether you are zipping a file or you are zipping a folder in Java where the whole directory structure is archived. But unzipping a file in Java doesn’t need such different functionalities. One Java program to unzip a file takes care of all the different functionalities. Unzip a file – Java program To unzip a file you need to follow the following steps- Read the compressed file from the zipped archive. For that class is used. From the ZipInputStream, zip entries for the files and directories are read using getNextEntry() method. If the entry is for a directory then you just need to create the directory. If the entry is for file then read the content of the file and write it to the destination file. Close the current entry using the closeEntry() method. Once all the zip entries are iterated close the input and output streams. public class UnzipFile { private static

How to Zip a Folder in Java

In the post How to Zip Files in Java we have seen how to zip a single file or multiple files in Java but you may also need to zip a folder in Java where you also retain the folder tree structure while zipping it. This post shows how to zip a folder in Java where the zip archive contains the whole tree structure (files and subdirectories). Options for zipping a folder in Java For zipping a folder with all its subfolders and files two options are given in this post. Using Files.walkFileTree method - Using this method you can recursively visit all the files in a file tree. An implementation of FileVisitor interface is provided to the Files.walkFileTree method to visit each file in a file tree. This option is available Java 7 onward . See example . By providing the code yourself to read the files with in a folder recursively by using listFiles() method in class. See example . Check this post How to Unzip a File in Java to see how to unzip files and folders i

How to Zip Files in Java

This post shows how you can zip files in Java. Using the options given here you can zip a single file or more than one file by specifying all those files. Zip a file in Java To zip files in Java there are two options- Using ZipOutputStream and ZipEntry classes residing in package. Using the Zip File System Provider - The zip file system provider treats a zip or JAR file as a file system and provides the ability to manipulate the contents of the file. The zip file system provider was introduced in the JDK 7 release. Want to zip a folder, check this post How to Zip a Folder in Java Table of contents Zipping single fie in Java using ZipOutputStream Zipping single fie in Java using Zip File System Provider Zipping multiple files in Java Zipping single fie in Java using ZipOutputStream The steps for zipping a file using ZipOutputStream are as follows- Create an InputStream for reading the source file. Create an OutputStream for th