I couldn't find out how to measure the time that a Thread is waiting locked. I have to determine if a Thread is waiting locked more than 1 second and if so to run another Thread instead. Thanks!
Try this:
long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();
long duration = endTime - startTime;
Time it using Sytem.nanoTime(); just before and after the wait.
long start = System.nanoTime();
wait();
long time = System.nanoTime() - start; // nanos
Or:
long start = System.nanoTime();
synchronized (objHere)
{
long time = System.nanoTime() - start; // nanos
// ...
}
Note: If a Thread is locked, the scheduler will continue with other Threads. You don't have to do this manually. That is the idea of threads. Maybe you are facing a deadlock? Wikipedia says it nicely:
A deadlock is a situation in which two or more competing actions are each waiting for the other to finish, and thus neither ever does.
Generally the methods which operates on locks accepts timeout as an argument. If you are using wait(), you can specify the amount of time by passing time to wait as argument. Check here for more details: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait%28long%29.
If you are using Lock, then try tryLock method of it which accepts time it has to wait. Check this tutorial for an idea: http://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html
Related
Is there a way to join a group of threads simultaneously with an overall timeout?
Suppose we have Collection<Thread> threads; and int timeout;. If I didn't care about the timeout, I would do
for (Thread t : threads)
t.join();
but I want to wait until either all threads are done, or a certain amount of time passes, whichever comes first. I was searching for a (hypothetical) ThreadGroup.join(int) which would do this.
Note that what I'm asking for is different from doing
for (Thread t : threads)
t.join(timeout);
Rather, I'm looking for something less verbose (and perhaps more reliable) than
int timeout = 10000;
for (Thread t : threads) {
if (timeout <= 0) break;
long start = System.currentTimeMillis();
t.join(timeout);
long end = System.currentTimeMillis();
// substract time elapsed from next timeout:
timeout -= (int) (end - start);
}
First create a single CountDownLatch having a count for every thread in the group.
A controlling thread can await(timeout, TimeUnit) on the latch.
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html#await-long-java.util.concurrent.TimeUnit-
Start the threads that are in the group.
Each of the threads in the group should decrement the latch when it completes.
The controlling thread will wait until everything in the group has completed or the timeout happens, and because await returns a boolean, the controlling thread can tell whether the latch was decremented naturally or whether a timeout occurred.
String startTime, endTime;
startTime = simpleDateFormat.format(Calendar.getInstance(TimeZone.getTimeZone(UTC_TIMEZONE)).getTime());
long time1 = System.nanoTime();
while (shouldRun) {
endTime = simpleDateFormat.format(Calendar.getInstance(TimeZone.getTimeZone(UTC_TIMEZONE)).getTime());
long time2 = System.nanoTime();
long pause = time2 - time1;
if (pause > threshold) {
LOG.info("Delay : {} ", pause);
}
time1 = time2;
startTime = endTime
}
In my understanding, I'm creating only 2 objects of String types, but I'm not very confident of my java memory management knowledge. By the way, shouldRun is always true, this thread is responsible of collecting some performance data about the application with whom it shares the JVM.
I've updated the code, the aim of this thread is to keep running and to measure (try to) SafePoint pauses.
It's impossible to tell, because the code you posted doesn't make the scope clear.
Usually I see start and end times as long, not String. Not useful in this form; can't calculate duration, for example.
Any memory that you finish using will automatically be cleaned up by the garbage collector (unless you do things that confuse the garbage collector such as keeping references lying around that you don't need any more).
At the end of this example you have two String references, you have created two strings and put them in those references. Anything else used will be tidied up for you.
I'm attempting to find the difference in running time between multi and single core solutions in Java. So far, the single core runs fine. However, I'm getting erratic reports from the multicore solution, some reporting that it took 0 nanoseconds, or slightly more.
The multicore reads as follow: (Notice that I'm not doing anything too advanced, just trying to find the length of time it ran. CPU execution time in Java convinced me to use System.nanoTime() instead of .currentTimeMillis() )
long start = System.nanoTime();
Runnable r0 = new FindMagicBrute(n);
Thread t0 = new Thread(r0);
Thread t1 = new Thread(r0);
Thread t2 = new Thread(r0);
t0.start();
t1.start();
t2.start();
long end = System.nanoTime();
System.out.println("Multithreaded run ended in " + (end-start) + " nanoseconds.");
Is there a way to determine when a thread has stopped executing?
You should wait for the threads to finish by calling join on each of them.
Otherwise, you're not timing anything but the time it takes to create the threads.
I have a program that will throw a simple exception when it's completed, when that exception is thrown is there any way to treat it like a stop-watch and stop the timer and display how long it took to solve the problem given?
Thanks a lot!
Milliseconds
System.currentTimeMillis() is a function that returns the current time in milliseconds. You can get invoke this function once when you start, and again when finished, then find the difference to determine the amount of time elapsed.
For example:
public void foo() {
long startTime = System.currentTimeMillis();
try {
doStuff();
} catch (Exception e) {
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println("This operation took " + elapsedTime + " milliseconds.");
}
}
Nanoseconds
You can also use System.nanoTime() which is precise to nanosecond (rather than to the millisecond), but it is more limited in how much of a difference it can portray.
In the simplest case, use System.currentTimeMillis() to record the start and stop times (subtracting start from stop in the catch block). There are more complicated approaches with pretty interfaces. See, for example:
Stopwatch class for Java
Just be sure that the timer is in scope whenever the exception is caught.
Exception handling is an especially poor method of flow control - much better to break out of a loop, set the loop conditional to false, or return out of your recursive method.
For your actual question, you can get the system time with System.currentTimeMillis() at the start of your program, and then again at the end, and compare. Note that the system call is only accurate to 15ms, so this is only really useful for long running programs.
Am I doing something really stupid here? I am trying to execute a method every minute or so, forever, or until I stop the program.
while(true) {
this.doSomethingPeriodically();
Calendar now = Calendar.getInstance();
int minutes = now.get(Calendar.MINUTE);
int resume = minutes + 1;
while (now.get(Calendar.MINUTE) < resume) {
// waiting for a minute
}
}
This code will never leave the loop. It's an endless loop, since the Calendar instance refered to by now won't change.
Also, what you try to do here is implement busy waiting which is a very bad idea (it uses CPU time doing nothing interesting).
The correct way to sleep is to use Thread.sleep().
the simplest way for execute tasks repeteadly in java is the java.util.TimerTask and java.util.Timer api.
A simple code is:
public class PrinterTimerTask extends java.util.TimerTask {
#Override
public void run() {
System.out.println( 'Current time is: ' + System.nanoTime() );
}
public static void main(String[] args) {
long delay = 0;
long period = 60000;
java.util.Timer timer = new java.util.Timer(threadName);
PrinterTimerTask task = new PrinterTimerTask();
timer = new Timer("SomeThreadNameForProfiler");
timer.schedule( task, delay, period );
}
}
Variables:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
More info:
Timer and TimerTask javadoc:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Timer.html
http://java.sun.com/j2se/1.5.0/docs/api/java/util/TimerTask.html
Another example:
http://www.javapractices.com/topic/TopicAction.do?Id=54
[]'s,
And Past
Try using the Timer class instead. It's meant for this sort of thing:
http://www.javapractices.com/topic/TopicAction.do?Id=54
https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html
Edit:
I just read that there's a newer replacement for Timer: ExecutorService. I've never used it, but it seems to have some advantages:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutorService.html
Java Timer vs ExecutorService?
Try using sleep instead, as it won't cause the processor to continue working on the thread:
Thread.sleep()
while(true) {
this.doSomethingPeriodically();
Thread.sleep(60000);
}
It would be better to use a Timer or at least use a sleep.
What you're trying to do here is called busy waiting. You are unnecessarily using huge amounts of CPU time (and you would even be using unnecessary memory if you fixed your bug and created a new Calendar instance in each loop).
What you actually want is the method Thread.sleep(), it is pretty well explained in a tutorial on sun.com.
It's better to use the sleep function: CurrentThread.sleep() and you specify the number of milliseconds that you want as a delay. It's better than busy waiting...