Java Timing a Task in Java – Find Out How!

  • Thread starter Thread starter frankfjf
  • Start date Start date
  • Tags Tags
    Java
AI Thread Summary
To implement a for loop that skips iterations if calculations exceed a specified time limit, threading is essential. The solution involves creating a new thread for each calculation within the loop, allowing for interruption after 20 seconds if the calculation is still running. This can be achieved using Java's ExecutorService to manage threads efficiently. The provided code demonstrates how to set up an ExecutorService with a single worker thread to execute lengthy calculations encapsulated in a Callable class. A Future object is used to retrieve results, with a timeout set to 20 seconds. If the calculation exceeds this time, a TimeoutException is caught, allowing the loop to skip to the next iteration. The approach ensures that lengthy calculations do not block the entire process, maintaining efficiency in execution.
frankfjf
Messages
166
Reaction score
0
Hi PF,

I am trying to write a program that utilizes a for loop that skips the current iteration (via continue) if it takes too long (for instance, longer than 20 seconds, else it finishes the current iteration as per normal), but am not sure how to best do this.

Does anyone know of a way to do this?
 
Technology news on Phys.org
Basically your problem boils down to needing the ability to interrupt a set of calculations at will. In this case, you want to interrupt a set of calculations inside a for loop after 20 seconds has passed on a given loop iteration, and then skip to the next iteration. To do this you need to use threading.

The general idea is to perform the calulations in a new Thread, which you will kill after 20 seconds if it is still running, start the thread inside your for loop and wait for it to finish before going to the next iteration. You can either do so directly, by creating a Runnable for your set of calculations, and a Thread instance for your Runnable, and using Thread.join to wait for the thread to die, and killing it internally after 20 seconds using either a Timer or System.currentTimeMillis(), or take advantage of the TimerTask class or ExecutorService interface (if you are using a newer version of java). Here is an example using ExecutorService:

Code:
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static java.lang.Math.random;

public class TestLoopInterrupt {

	public static void main(String[] args) {
		
		// Create an array with 10 calculation objects
		CalculationObject[] calcObjects = new CalculationObject[10];
		
		/* This is our for loop where we will do lengthy calculations 
		on a bunch calculation objects in an array. Each call to 
		performCalculation() will last a maximum of 20 seconds*/
		for(CalculationObject o : calcObjects) {
			/*Create a calculation object with some random number as an
			 attribute and then perform some lenghty calculations on it
			 and output the result */	
			o = new CalculationObject((double)(random()*10));
			System.out.println("Number was " + o.getNum());
			o = performCalculation(o);
			System.out.println("Number is " + o.getNum());
		}		
	}
	
	private static CalculationObject performCalculation(CalculationObject o) {
		/*Create an Executor that uses a single worker thread operating
		off an unbounded queue*/
		final ExecutorService service = Executors.newSingleThreadExecutor();
		
		/*Create instance of our LengthyCalculation class, passing our
		Calculation Object as a parameter to be used in the calculation*/
		LengthyCalculation lengthyCalculation = new LengthyCalculation(o);

        try {
        	//Use a Future to represent the result of our calculations
            final Future<CalculationObject> f = service.submit(lengthyCalculation);
            /*Get the result, waiting up to 20 seconds. 
            A TimeoutException is thrown if the calculation has not been
            completed in 20 seconds.*/
            o = f.get(20, TimeUnit.SECONDS);
        } catch (final TimeoutException e) {
            System.err.println("Calculation took to long");
        } catch (final Exception e) {
            throw new RuntimeException(e);
        } finally {
            service.shutdown();
			service.shutdownNow();
        }
        
        return o;
	}

}

Code:
//Some object that contains attributes we will perform calculations on
public class CalculationObject {
	private double num;
		
	public CalculationObject(double num) {
		this.num = num;
	}
		
	public double getNum() {
		return num;
	}
}

Code:
import java.util.concurrent.Callable;

public class LengthyCalculation 
			 implements Callable<CalculationObject> {
			 
	private CalculationObject o;
		
	public LengthyCalculation(CalculationObject o) {
		this.o = o;
	}
	
	@Override
	public CalculationObject call() throws Exception {
		double num = o.getNum();
		while(num<5) {
			num += 0.0000000004;
		}
		return new CalculationObject(num);
	}
		
}

This performs some lengthy calculation on some calculation objects in an array, using a for loop. If any of the lentghy calculations take longer than 20 seconds to execute, the calculation is topped and the next ieration of the for loop is processed.
 
Oh yeah, I figured I would need threading but wasn't sure how to go about getting started on it. This could work well, thank you.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...
Back
Top