Skip to main content

Posts

Showing posts from March, 2021

Java ScheduledThreadPoolExecutor - Scheduling With ExecutorService

ScheduledThreadPoolExecutor in Java adds functionality to schedule commands to run after a given delay, or to execute periodically. Since ScheduledThreadPoolExecutor is an ExecutorService so it uses thread from a thread pool to execute tasks. Table of contents Java ScheduledThreadPoolExecutor Java ScheduledThreadPoolExecutor constructors Creating ScheduledThreadPoolExecutor instance using Executors factory methods Scheduling methods in Java ScheduledThreadPoolExecutor Java ScheduledThreadPoolExecutor example – Scheduling Runnable Java ScheduledThreadPoolExecutor’s scheduleAtFixedRate() method example Java ScheduledThreadPoolExecutor’s scheduleWithFixedDelay() method example Java ScheduledThreadPoolExecutor example using constructor Java ScheduledThreadPoolExecutor ScheduledThreadPoolExecutor class is part of Java Executor framework with in the Java concurrent API. This class extends ThreadPoolExecutor and implements ScheduledExecutorService i

Multiple Catch Blocks in Java

If hearing the term try-catch block is giving you an idea that you can have a try block and a single associated catch block then that is a wrong idea. You can have multiple catch blocks associated with a try block . In this post we’ll see examples of multiple catch blocks in Java exception handling. Refer Multi-Catch Exception in Java to seen another way of grouping multiple catch blocks using multi-catch statement available from Java 7. You enclose the code that may throw an exception in try block but the enclosed code may throw more than one exception too. In order to handle these exceptions you can provide multiple catch blocks in Java. If an exception is thrown the exception handling mechanism looks for the catch block with an argument that matches the type of the exception thrown. Only the matching catch clause out of the multiple catch blocks is execute d. After the matching catch block is executed, execution continues after the try-catch block. Example of multiple

How to Read Delimited File in Java

If you have to read delimited file in Java and parse it then you can do it using the following two ways- Using Scanner class with useDelimiter() method. Read file using BufferedReader line by line and then split each line using split() method. Using Scanner class to read delimited file in Java A Scanner breaks its input into tokens using a delimiter pattern, which by default matches white space. The scanner can also use delimiters other than white space for that useDelimiter() method is used. Let’s see some examples of using Scanner class to read delimited file in Java. Reading CSV file using Scanner in Java Here is an example CSV file which denotes Account From, Account To and Amount Transferred. 1001,1003,2000 1006,2004,3000 1005,1007,10000 Which you want to read using Scanner class and parse it to display the fields. import java.io.File; import java.io.IOException; import java.util.Scanner; public class ReadDelimited { public static void main(String[] arg

How to Read Input From Console in Java

If you have to read input from console in Java there are 3 options. Using BufferedReader class. See example . Using Scanner class, available from Java 5. See example . Using System.console() method, available from Java 6. See example . Using BufferedReader class By wrapping the standard input stream "System.in" in an InputStreamReader which is further wrapped with in a BufferedReader you can read input from console in Java. public class ConsoleReader { public static void main(String[] args) { // Wrapping InputStreamReader and System.in BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter City Name: "); try { String cityName = bufferRead.readLine(); System.out.println("Entered city name- " + cityName); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Output Enter City Name

Java Volatile Keyword With Examples

In this post we’ll see what is volatile keyword in Java, when to use volatile variable and what is the reason for declaring variable as volatile. Table of contents What is volatile keyword in Java How declaring variable as volatile in Java helps Volatile Java example code Volatile ensures reordering of statements doesn’t happen Volatile ensures visibility not atomicity Important points about volatile in Java What is volatile keyword in Java To know volatile keyword in Java better you would have to know a little about the optimizations that happens for the variables with in the Java memory model. Let’s say you have a variable test declared in your code. You would think that test variable will be stored only in RAM and all the threads will read the value of the test variable from there. But the processors, in order to make processing faster, would hold the value of the variable in its cache . In that case any change to the value is written back to the

ThreadLocal Class in Java With Examples

In a multi-threaded environment a shared object would need synchronization to avoid corruption through concurrent access, but synchronization is expensive. Another alternative is to give each thread its own instance and avoid sharing of data. That’s what ThreadLocal class in Java does. ThreadLocal class in Java provides thread local variables where each thread has its own, independently initialized copy of the variable. How to create and access thread-local variables Using ThreadLocal() constructor you can create a thread local variable. For example if you want to create a thread local variable that stores an integer value for individual threads. private static final ThreadLocal<Integer> tcValue = new ThreadLocal<Integer>(); Here note that ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread. To get or set value to this thread local variable you can use get() and set() methods of the ThreadLocal class

Sleep Method in Java Multi-Threading

Thread.sleep() method in Java multi-threading causes the currently executing thread to suspend execution for a specified period. In Java Thread class there are two overloaded sleep() methods- static void sleep(long millis) throws InterruptedException - Causes the currently executing thread to sleep for the specified number of milliseconds. static void sleep(long millis, int nanos) throws InterruptedException - Causes the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds. Important points about sleep() method in Java If the value of milliseconds is negative then IllegalArgumentException is thrown. If the value of nanoseconds is not in the range 0-999999 then IllegalArgumentException is thrown. Though you provide the duration thread is supposed to sleep as an argument in sleep method but that depends on the precision and accuracy of system timers and how schedulers are implemented in underlying

isAlive() And join() Methods in Java

In your application you may have a scenario where you spawn a bunch of threads to execute some logic and you want to start any further processing only after all the threads have finished the execution. Which means you need some way to know whether a thread is terminated or not. For that purpose Thread class provides isAlive() and join() methods in Java to check if a thread has finished executing or not. isAlive() method in Java This method tests if this thread is alive. A thread is alive if it has been started and has not yet died. Method returns true if thread is alive otherwise it returns false. isAlive() method syntax public final boolean isAlive() join() method in Java This method waits until the thread on which it is called terminates. There are three overloaded versions of join() method in Java Thread class. public final void join() throws InterruptedException - Waits indefinitely for this thread to die. public final void join(long millis) throws Interrupted

Livelock in Java Multi-Threading

In a multi-threaded environment a thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread then a livelock may happen if two or more threads are busy responding to the action of each other and unable to make further progress in the process. If we take example of three threads where- Thread-1 is acting on a response from Thread-2 Thread-2 is acting on a response from Thread-3 Thread-3 is acting on a response from Thread-1 So these three threads are busy responding to the action of each other thus unable to make any progress because of livelock. How livelock is different from deadlock In case of livelock, just like deadlock , threads don’t make any progress but they are not blocked as the case with deadlock. Threads are active but they are busy responding to each other thus not making any progress. Java livelock example In the example there are two threads for customer and

Thread Starvation in Java

In a multi-threaded environment access to shared resources is synchronized so that at any given time only a single thread can enter a synchronized context. Theoretically all the threads trying to gain access to a synchronized block or method should get some CPU time periodically but in practice that may not happen. If a thread is unable to gain regular access to shared resources and is unable to make progress it is called thread starvation in Java multi-threading . Why does thread starvation happen Thread starvation may happen because of the following reasons. Suppose an object has a synchronized method that requires some heavy processing and takes long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. Threads with higher priority are scheduled to run first and taking all the CPU time causing the thread with minimum priority to keep on waiting to be scheduled to ru

Deadlock in Java With Examples

In a multi-threaded environment there may come a situation when one thread is waiting for a resource that is locked by another thread, which in turn is waiting for another thread and so on until this dependency loops back to the first waiting thread. Thus all the threads are waiting for each other to release the resources to make any further progress and blocked forever in the process. This scenario is called deadlock in multi-threading. Deadlock example To explain deadlock in Java we can take a simple scenario of two threads Thread1 and Thread2, where Thread1 holds a lock on obj1 and waiting to acquire a lock on obj2 . At the same time Thread2 has a lock on obj2 and waiting to acquire lock on obj1 . Here both threads are blocked in a circular loop where Thread1 is waiting to acquire lock on obj2 and Thread2 is waiting to acquire lock on obj1 thus creating a deadlock. Table of contents Deadlock in Java scenarios Deadlock in Java example How to avoid deadl