[Java] Execute a specific process in another thread with Executor Service [Avoid infinite loop]

Introduction

This is a sample that executes a specific process in Java in another thread. When an infinite loop occurs in a certain process (when the process is not completed within the specified time), it is necessary to interrupt the process and generate an error, so it is a memorandum at that time.

sample

main.java



package main;


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;


public class Main {
	
	public static void main(String[] args) {
		int a = 1;
		int b = 2;
		int c = 3;
		
		ExecutorService exec = Executors.newSingleThreadExecutor();
		//Execute processing in another thread
		Future<Integer> future = exec.submit(new ExcutorSample(a, b, c));
		Integer result = 0;
		try{
			//Wait 10 seconds. If the process ends correctly, the calculation result will be returned. Throw an exception after 10 seconds
			result = future.get(10, TimeUnit.SECONDS);
		} catch(TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} finally {
			//Suspend processing. This process is harmless even if the process is completed normally.
			future.cancel(true);
		}
        
		System.out.println(result);
		  
	}

	public static class ExcutorSample implements Callable<Integer>{
		private int a;
		private int b;
		private int c;

		public ExcutorSample(int a, int b, int c){
			this.a = a;
			this.b = b;
			this.c = c;
		}
	    
		@Override
		public Integer call() throws Exception {
			//Built-in infinite loop processing
			boolean loopFlg = true;
			while(loopFlg) {
				Thread.sleep(1000);
				System.out.println("In a loop");
			}
			return a + b + c;
		}
	}
}

Execution result

In a loop
In a loop
In a loop
In a loop
In a loop
In a loop
In a loop
In a loop
In a loop
In a loop
java.util.concurrent.TimeoutException
	at java.util.concurrent.FutureTask.get(FutureTask.java:205)
	at main.Main.main(Main.java:24)
0

in conclusion

Don't generate an infinite loop

Recommended Posts

[Java] Execute a specific process in another thread with Executor Service [Avoid infinite loop]
I can't create a Java class with a specific name in IntelliJ
thread safe process in java language
Split a string with ". (Dot)" in Java
Read a string in a PDF file with Java
Create a CSR with extended information in Java
Let's create a timed process with Java Timer! !!
Quickly implement a singleton with an enum in Java
Output true with if (a == 1 && a == 2 && a == 3) in Java (Invisible Identifier)
Use java1.7 (zulu7) under a specific directory with jenv
I'm like writing a process that keeps increasing itself (list) in a list loop in Java (at work)