Wednesday 27 October 2021

How to call a method asynchronously in Java?

In this post, I am going to explain how to call a method asynchronously.

 

Approach 1: Using threads

 

Example

new Thread(() -> {
	// Method to execute
	Printer.sayHello(2);
}).start();

 

Find the below working application.

 

Printer.java

 

package com.sample.app.threads;

public class Printer {
	
	public static void sayHello(int sleepInSeconds) {
		while(true) {
			SleepUtil.sleepForNSeconds(sleepInSeconds);
			System.out.println("Hello!!!!!");
		}
		
	}

}

 

SleepUtil.java

package com.sample.app.threads;

import java.util.concurrent.TimeUnit;

public class SleepUtil {
	public static void sleepForNSeconds(int secondsToSleep) {
		try {
			TimeUnit.SECONDS.sleep(secondsToSleep);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

AsyncExecOfMethodUsingThreads.java

package com.sample.app.threads;

public class AsyncExecOfMethodUsingThreads {

	public static void main(String args[]) {
		new Thread(() -> {
			Printer.sayHello(2);
		}).start();

		while (true) {
			SleepUtil.sleepForNSeconds(2);
			System.out.println("Hi!!!");
		}

	}

}


Sample Output

Hi!!!
Hello!!!!!
Hello!!!!!
Hi!!!
Hello!!!!!
Hi!!!
Hello!!!!!
Hi!!!
Hi!!!
Hello!!!!!


Approach 2: Using CompletableFuture.runAsync.

 

Example

CompletableFuture.runAsync(() -> {
	// Method to execute asynchronously.
	Printer.sayHello(2);
});


AsyncExecOfMethodUsingCompletableFeature.java

package com.sample.app.threads;

import java.util.concurrent.CompletableFuture;

public class AsyncExecOfMethodUsingCompletableFeature {

	public static void main(String args[]) {

		CompletableFuture.runAsync(() -> {
			// Method to execute asynchronously.
			Printer.sayHello(2);
		});

		while (true) {
			SleepUtil.sleepForNSeconds(2);
			System.out.println("Hi!!!");
		}

	}

}


Sample Output

Hi!!!
Hello!!!!!
Hi!!!
Hello!!!!!
Hi!!!
Hello!!!!!
Hi!!!
Hello!!!!!
Hi!!!
Hello!!!!!


Approach 3: Using ForkJoinPool.commonPool().execute() method

 

Example

ForkJoinPool.commonPool().execute(() -> {
	// Method to execute asynchronously.
	Printer.sayHello(2);
});


AsyncExecOfMethodUsingForkJoinPool.java

package com.sample.app.threads;

import java.util.concurrent.ForkJoinPool;

public class AsyncExecOfMethodUsingForkJoinPool {

	public static void main(String args[]) {

		ForkJoinPool.commonPool().execute(() -> {
			// Method to execute asynchronously.
			Printer.sayHello(2);
		});

		while (true) {
			SleepUtil.sleepForNSeconds(2);
			System.out.println("Hi!!!");
		}

	}

}


Approach 4: Using Executors.newSingleThreadExecutor().submit()

Executors.newSingleThreadExecutor().submit(() -> {
	// Method to execute asynchronously.
	Printer.sayHello(2);
});


AsyncExecOfMethodUsingSingleThreadExecutor.java

package com.sample.app.threads;

import java.util.concurrent.Executors;

public class AsyncExecOfMethodUsingSingleThreadExecutor {

	public static void main(String args[]) {

		Executors.newSingleThreadExecutor().submit(() -> {
			// Method to execute asynchronously.
			Printer.sayHello(2);
		});

		while (true) {
			SleepUtil.sleepForNSeconds(2);
			System.out.println("Hi!!!");
		}

	}

}


Approach 5: Using thread pool.

 

Example

ExecutorService asyncExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

asyncExecutor.execute(() -> {
	// Method to execute asynchronously.
	Printer.sayHello(2);
});


AsyncExecOfMethodUsingThreadPool.java

package com.sample.app.threads;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncExecOfMethodUsingThreadPool {

	public static void main(String args[]) {

		ExecutorService asyncExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

		asyncExecutor.execute(() -> {
			// Method to execute asynchronously.
			Printer.sayHello(2);
		});

		while (true) {
			SleepUtil.sleepForNSeconds(2);
			System.out.println("Hi!!!");
		}

	}

}


 

 

You may like

Interview Questions

Understanding ConcurrentModificationException in Java

Remove oldest entry from the map

Synthetic constructs in Java

What is bridge method in Java?

How HashSet behave while adding a duplicate value?

No comments:

Post a Comment