start a thread which terminates the process after a specified time - java

I am executing a program for a network where i have a certain number of tasks execution in loop, it works fine but when there a any flaws occurs due to network problem it got stuck in one of any task. so i want to create a thread which start at the time when control goes in to loop and after some delay it terminate it self with continuing the process.
for example-
for ( /*itearting condition */)
{
//thread start with specified time.
task1;
task2;
task3;
//if any execution delay occur then wait till specified time and then
//continue.
}
Please give me some clue regarding this, a snippets can help me a lot as i need to fix it shortly.

A thread can only be terminated with its cooperation (assuming you want to save the process). With the thread's cooperation, you can terminate it with any termination mechanism it supports. Without its cooperation, it cannot be done. The usual way to do it is to design the thread to sanely handle being interrupted. Then you can have another thread interrupt it if too much time passes.

I think you may need something like this:
import java.util.Date;
public class ThreadTimeTest {
public static void taskMethod(String taskName) {
// Sleeps for a Random amount of time, between 0 to 10 seconds
System.out.println("Starting Task: " + taskName);
try {
int random = (int)(Math.random()*10);
System.out.println("Task Completion Time: " + random + " secs");
Thread.sleep(random * 1000);
System.out.println("Task Complete");
} catch(InterruptedException ex) {
System.out.println("Thread Interrupted due to Time out");
}
}
public static void main(String[] arr) {
for(int i = 1; i <= 10; i++) {
String task = "Task " + i;
final Thread mainThread = Thread.currentThread();
Thread interruptThread = new Thread() {
public void run() {
long startTime = new Date().getTime();
try {
while(!isInterrupted()) {
long now = new Date().getTime();
if(now - startTime > 5000) {
//Its more than 5 secs
mainThread.interrupt();
break;
} else
Thread.sleep(1000);
}
} catch(InterruptedException ex) {}
}
};
interruptThread.start();
taskMethod(task);
interruptThread.interrupt();
}
}
}

Related

how to get actual thread execution time in java

I am trying to measure the time that a thread takes to execute.
I have created a sample programme
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class Sample {
public static void main(String[] args ) {
ThreadPoolExecutor exec = (ThreadPoolExecutor)Executors.newFixedThreadPool(1000);
for(int i=0; i<1000; i++) {
exec.execute(new Runnable() {
#Override
public void run() {
long start = System.currentTimeMillis();
try{
Thread.sleep(10000);
} catch(Exception ex) {
ex.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("[Sample] Thread id : " + Thread.currentThread().getId() + ", time : " + (end - start));
}
});
}
}
}
Each thread sleeps for 10 seconds. So the duration = (end - start) should be 10000. But some threads are taking more time than expected. I am guessing this also includes thread switching time and and blocking time. Is there a way to measure the exectution time in threaded programme in JAVA?
The thing is that I have a programme that makes network calls in threads. So even if the socket time out is say 60 seconds, the thread execution time is close to 2 minutes. My guess is that the above way of calculating execution time also accounts for thread switching time and blocking time. It is not measuring the actual thread execution time
Thanks.
For such cases I use JavaVisualVM, it is a very very handy tool for finding concurrency issues.
I ran your code locally and this is what visual VM shows me.
All of the threads have exactly the same sleep time, so the differences we are seeing in the console log are probably misleading.

How to restart an update loop of an application

I am working on a drawing application, using Java and Swing. It has a constant update loop that runs constantly, as long as a boolean variable is set to true. The loop is located inside a thread.
It works fine, but now I want the loop to only run at certain times (only when the mouse is pressed), and otherwise not run. (Thus not wasting memory for nothing).
To stop the loop, I can simply set that variable to false. But my question is, how can I restart the loop after stopping it? Setting that variable back to true will not restart the loop. What would be a good way to do this?
EDIT: My (a little simplified) loop:
public void run(){
int TICKS_PER_SECOND = 50;
int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
int MAX_FRAMESKIP = 10;
long next_game_tick = System.currentTimeMillis();
int loops;
boolean app_is_running = true;
while( app_is_running ) {
loops = 0;
while( System.currentTimeMillis() > next_game_tick && loops < MAX_FRAMESKIP) {
update();
next_game_tick += SKIP_TICKS;
loops++;
}
repaint();
}
}
Use Object.wait to suspend the thread when it isn't running. Have another thread call Object.notify to wake it up from its sleep.
To execute the thread body once every FRAME_RATE ms while being controllable by an externally defined Boolean, the run method could be structured as such:
public void run()
{
long delay;
long frameStart = System.currentTimeMillis();
// INSERT YOUR INITIALIZATION CODE HERE
try
{
while (true)
{
if (active) // Boolean defined outside of thread
{
// INSERT YOUR LOOP CODE HERE
}
frameStart += FRAME_RATE;
delay = frameStart - System.currentTimeMillis();
if (delay > 0)
{
Thread.sleep(delay);
}
}
}
catch (InterruptedException exception) {}
}
Additionally, if you want to eliminate the slight overhead of the constantly running loop (for a mostly inactive thread), the Boolean in the while loop could be replaced with a Semaphore object:
while (true)
{
semaphore.acquire(); // Semaphore defined outside thread with 1 permit
// INSERT YOUR LOOP CODE HERE
semaphore.release();
frameStart += FRAME_RATE;
delay = frameStart - System.currentTimeMillis();
if (delay > 0)
{
Thread.sleep(delay);
}
}
To stop the loop externally use semaphore.acquire(); to restart it use semaphore.release().

How to run a Thread for a user specified amount of time?

Am creating a program that is based on mixing and making perturbation in a population containing solutions Vector.
So I created a for loop that stops after a certain time given by the user.
Inside the loop, am going to call 5 procedures and I thought that if i put each procedure in a thread will make the program making more solutions in a same time than calling normal methods.
Here 5 created the 5 threads, but when i start them the don't want to stop even if i use the Thread.stop, Thread.suspend, Thread.interrupt or Thread.destroy
Here is my code and could u help me with your ideas ?
I have inserted a new variable :
public volatile boolean CrossOpb = true;`
Here is my code:
Thread CrossOp = new Thread(new Runnable() {
public void run() {
while(CrossOpb == true){
int rdmCross2=(int) (Math.random() * allPopulation.size()) ; // Crossover 1st vector
int rdmCross1=(int) (Math.random() * allPopulation.size()) ;
Vector muted = new Vector();
Vector copy = copi((Vector) allPopulation.get(rdmCross2));
Vector callp = copi((Vector) allPopulation.get(rdmCross1));
muted = crossover(callp, copy);
System.out.println("cross over Between two Randoms ----------->");
affiche_resultat(muted);
allPopulation.add(muted);
}
}
});
The loop :
CrossOp.setDaemon(true);
int loop = 1;
long StartTime = System.currentTimeMillis() / 1000;
for (int i = 0; i < loop; ++i) {
loop++;
if (timevalue < ((System.currentTimeMillis() / 1000) - StartTime)) {
loop = 0;
CrossOpb = false;
}
CrossOp.start();
}
I already answered to a similar question. In that case, it was C#, but the concept is the same.
You must not kill threads. Threads must exit on their own will.
Just put a volatile boolean variable somewhere, and set it to true/false, when you want your thread to terminate, then, in the thread, replace the while (true) with a while (myVariable == true/false).
Anyway, you say:
Inside the loop, am going to call 5 procedures ant i thought that if i put each procedure in a thread will make the program making more solutions in a same time than calling normal methods.
Well, that's generally false. If the procedures are data-dependent (each of them depends on the results of the previous one), putting them on threads will change nothing. It might be smarter to put iterations in a pipeline, so that you have 5 threads executing steps of successive iterations. I'm not sure if that's possible for genetic algorithms, and anyway you'll have to handle some special case (e.g. a mutation, that alters the population of partially computed iterations).
How to run a Thread for a specific amount of time:
Here is the basic approach is to keep calculate how long the Thread has run and exit and return the result, which in our case here is details on how long the Thread executed.
NOTE: you must use System.nanoTime() as System.currentTimeMillis() will just return the same thing every time you call it in the method.
I use a Random number to calculate different lifetimes for each of the Callables so that you can see that they don't execute exactly for the time specified but they are very very close, and the variance of the delta is pretty consistent, at least on my machine.
Here a Gist of the code below for easier access.
package com.stackoverflow.Q18818482;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
public class Question18818482
{
public static Random RND;
static
{
RND = new Random();
}
public static void main(final String[] args)
{
try
{
final ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
final List<Future<String>> results = new ArrayList<>(10);
for (int i = 0; i < 10; i++)
{
results.add(es.submit(new TimeSliceTask(RND.nextInt(10), TimeUnit.SECONDS)));
}
es.shutdown();
while(!results.isEmpty())
{
final Iterator<Future<String>> i = results.iterator();
while (i.hasNext())
{
final Future<String> f = i.next();
if (f.isDone())
{
System.out.println(f.get());
i.remove();
}
}
}
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
catch (ExecutionException e)
{
throw new RuntimeException(e);
}
}
public static class TimeSliceTask implements Callable<String>
{
private final long timeToLive;
private final long duration;
public TimeSliceTask(final long timeToLive, final TimeUnit timeUnit)
{
this.timeToLive = System.nanoTime() + timeUnit.toNanos(timeToLive);
this.duration = timeUnit.toMillis(timeToLive);
}
#Override
public String call() throws Exception
{
while( timeToLive <= System.nanoTime() )
{
// simulate work here
Thread.sleep(500);
}
final long end = System.nanoTime();
return String.format("Finished Elapsed Time = %d, scheduled for %d", TimeUnit.NANOSECONDS.toMillis(timeToLive - end), this.duration );
}
}
}
Here is what one runs output looks like
NOTE: All times are in milliseconds
Finished Elapsed Time = 999, scheduled for 1000
Finished Elapsed Time = 2998, scheduled for 3000
Finished Elapsed Time = 5999, scheduled for 6000
Finished Elapsed Time = 1994, scheduled for 2000
Finished Elapsed Time = 8994, scheduled for 9000
Finished Elapsed Time = 6993, scheduled for 7000
Finished Elapsed Time = 6993, scheduled for 7000
Finished Elapsed Time = 5993, scheduled for 6000
Finished Elapsed Time = 5998, scheduled for 6000
After reading the whole last night about threads, i have discovered that the solution for my problem was not that hard.
The idea was to edit the condition of the stopping loop inside the thread so we control it by giving it a specific amount of time to run for it and here is my Example :
class ProcessorCordm extends Thread {
int runningtime;
public ProcessorCordm(int runningtime) {
this.runningtime = runningtime;
}
public void run() {
int loop = 1;
long StartTime = System.currentTimeMillis() / 1000;
for (int i = 0; i < loop; ++i) {
int rdmCross2 = (int) (Math.random() * allPopulation.size()); // Crossover 1st vector
int rdmCross1 = (int) (Math.random() * allPopulation.size());
Vector muted = new Vector();
Vector copy = copi((Vector) allPopulation.get(rdmCross2));
Vector callp = copi((Vector) allPopulation.get(rdmCross1));
muted = crossover(callp, copy);
System.out.println("cross over Between two Randoms ----------->");
affiche_resultat(muted);
addsolution(muted);
loop++;
if (timevalue < ((System.currentTimeMillis() / 1000) - StartTime)) {
loop = 0;
}
}
}
}
So if i want to run my Thread for 10 seconds i only need to :
ProcessorCoG CrossOpg = new ProcessorCoG(10);
And fo my case, I have to call many Threads simultaneously working for a specific TimeValue so i used the ExecutorServiceClass :
ProcessorCoG CrossOpg = new ProcessorCoG(timevalue);//extends Thread class
ProcessorCordm CrossOp = new ProcessorCordm(timevalue);//extends Thread class
ProcessorCordm CrossOp2 = new ProcessorCordm(timevalue);//extends Thread class
MutateGb MutGb = new MutateGb(timevalue);//extends Thread class
MutateRdm MutRdm = new MutateRdm(timevalue);//extends Thread class
MbsRdm MbsR = new MbsRdm(timevalue);//extends Thread class
ExecutorService executor = Executors.newFixedThreadPool(6);
executor.submit(MutGb);
executor.submit(MutRdm);
executor.submit(CrossOp);
executor.submit(CrossOp2);
executor.submit(CrossOpg);
executor.submit(MbsR);

How do I print summary message after all threads (in a pool) complete? [duplicate]

This question already has answers here:
ExecutorService, how to wait for all tasks to finish
(16 answers)
Closed 5 years ago.
I have a command line application. It runs a loop say 100 times and in the loop schedules a task using a thread. I am using ExecutorService so there are 4 threads running at any time.
After the loop ends, I want to print a summary message. E.g. time taken to complete all 100 tasks. When I stepped through the code the debugger went straight to the summary part, but the other tasks are still running. I understand this is because each thread runs on its own. So how do I print messages only after all threads complete?
ExecutorService exec = Executors.newFixedThreadPool(4);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
Runnable requestHandler = new Runnable() {
#Override
public void run() {
try {
// call task function in here
} catch (Exception ex) {
}
}
};
exec.execute(requestHandler);
}
exec.shutdown();
long endTime = System.currentTimeMillis();
LOGGER.info("******************SUMMARY******************");
LOGGER.info("Time taken : " + ((endTime - startTime)/1000) + " seconds, "
+ ((endTime - startTime)/1000/60) + " minutes");
From the main-thread, you could create another thread that does everything from declaring exec to exec.shutdown();. After creating this thread, you put the main-thread to wait. At the end of the new thread's actions(after exec.shutdown();) you should notify it.
See http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html example copied for brevity
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
Basically you need to wait until the ExecutorService isTerminated() method returns true. You can use awaitTermination() to that end.
The solution for you based on your code:
ExecutorService exec = Executors.newFixedThreadPool(4);
long start = System.currentTimeMillis();
//Your code
exec.shutdown();
while(true) {
if(exec.isTerminated()) {
long end = System.currentTimeMillis();
System.out.println("Time : " + (end - start));
break;
}
Check this out! It works!

java- timing the execution of a block of code

hi
i want a block of code(certain lines of a function) that will run for a stipulated amount of time (say x milliseconds).Is is possible to do this in java?
1st approach:
long startTime = System.nanoTime();
while(System.nanoTime() - startTime < MAX_TIME_IN_NANOSECONDS){
// your code ...
}
2nd approach
Start your code in thread.
Sleep main thread for as long as you need.
Kill (stop, interrupt) your thread.
either use an exit condition based on current timestamp, or create a separate thread and kill it after a specified timeout.
Run your method in a separate thread, but passing it to an Executor. You can then use the Future to wait a certain period of time for the the thread to complete. If it doesn't complete, you will get a TimeoutException and you can then cancel the thread. Cancelling the thread causes the thread to be interrupted. So your code will have to periodically check the thread's interrupted status and exit if necessary.
For example:
ExecutorService exec = Executors.newSingleThreadExecutor();
Future<Integer> future = exec.submit(new Callable<Integer>(){
#Override
public Integer call() throws Exception {
//do some stuff
//periodically check if this thread has been interrupted
if (Thread.currentThread().isInterrupted()) {
return -1;
}
//do some more stuff
//check if interrupted
if (Thread.currentThread().isInterrupted()) {
return -1;
}
//... and so on
return 0;
}
});
exec.shutdown();
try {
//wait 5 seconds for the task to complete.
future.get(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
//the task did not complete in 5 seconds
e.printStackTrace();
System.out.println("CANCELLING");
//cancel it
future.cancel(true); //sends interrupt
}
You could use Calendar:
timeInMilis = Calendar.getInstance().getTimeInMillis();
while(Calendar.getInstance().getTimeInMilis() - timeInMilis < MAX_TIME_IN_MILIS){
// Execute block
}
Check the time using System.currentTimeMillis() and exit your loop after the time has passed.
long endTime = System.currentTimeMillis() + ClassName.EXECUTION_TIME_MS;
while (System.currentTimeMillis() < endTime) {
// do your stuff
}
If you need to sleep inside the thread for some reason, adjust your sleep time to end at the end time.
long timeLeft = endTime - System.currentTimeMillis();
if (sleepAmount > timeLeft)
sleepAmount = timeLeft;
Thread.sleep(sleepAmount);
If you're going to use the wait() and notify() method, then use the calculated timeLeft as the argument to wait() to ensure the maximum wait time. Once that wait time hits, the method will return and the loop will break.
long timeLeft = endTime - System.currentTimeMillis();
if (timeLeft > 0)
this.wait(timeLeft);
If you're running multiple steps inside the loop which can take a long time, you should add additional checks between steps, if you want the process to break between steps, to exit the loop if the designated time has passed. This is a design decision. When the timer expires, do you want the task to finish up the step it's working on and then exit? It's up to you how to code it based on the desired result.
long endTime = System.currentTimeMillis() + ClassName.EXECUTION_TIME_MS;
while (System.currentTimeMillis() < endTime) {
this.doFirstLongThing();
if (System.currentTimeMillis() >= endTime) break;
this.doSecondLongThing();
if (System.currentTimeMillis() >= endTime) break;
this.doThirdLongThing();
}

Categories