I want to measure the full execution time (so when ALL threads are done).
The trick with System.currentimeMillis won't work here, because when the main-method ends, my own created threads will still be running because they take longer time to process than the main-method.
How Can I do this?
I'll give an example.
public class Main {
public static void main(String[] args) {
long start = System.currentTimeMillis();
new Thread(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
long end = System.currentTimeMillis();
System.out.println(end - start); // Won't work because my new Thread will still be running here.
}
}
You can use an ExecutorService:
long startTime = System.nanoTime();
ExecutorService executorService = Executors.myPool();
for(conditions)
executorService.submit(new myThread());
Then don't forget to shutdown():
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.
executorService.shutdown();
And wait:
Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
executorService.awaitTermination(1, TimeUnit.HOUR); // however long you need
Then calculate:
long totalTime = System.nanoTime() - startTime;
System.out.printf("The total time everything took was %.3f ms %n", totalTime/1e6);
You should consider using thread Joins before measuring the end time. That will ensure that the main thread exit only when all other threads exit.
package threadsync;
public class MeasureRunningTime {
public static void main(String[] args) {
long start = System.currentTimeMillis();
Thread th = new Thread(){
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
};
th.start();
try {
th.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("The thread took:" + (end - start) + "ms");
}
}
Output in this case should be:
The thread took:5003ms
Related
The timeout on b.wait(1000) instruction is not executing after 1 second.
I will appreciate some help on how to execute the timeout on the wait() method.
protected void onCreate(Bundle savedInstanceState) {
ThreadB b = new ThreadB();
b.start();
synchronized (b) {
try {
long start = System.currentTimeMillis();
Log.i(TAG, "Before Wait has started "+start);
b.wait(1000);
long finish = System.currentTimeMillis();
Log.i(TAG, "After Wait has finished "+finish);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
}
class ThreadB extends Thread {
#Override
public void run() {
synchronized (this) {
long start = System.currentTimeMillis();
Log.i(TAG, "*** Thread Start "+start);
Random ran = new Random();
for (int i = 0; i < 1E7; i++) {
Math.sin(ran.nextDouble());
}
long finish = System.currentTimeMillis();
Log.i(TAG, "*** Thread Finish "+finish);
notify();
}
}
}
Your program has a "race" to acquire the lock on the ThreadB object. If the main thread wins the race, the timeout logic works. If the new thread wins, the main thread has to wait for the new thread to finish so that it can grab the lock, and after that then it will call Object.wait and sleep for 1 second.
One quick fix is to make sure that the main thread has the lock before the new thread starts:
ThreadB b = new ThreadB();
synchronized (b) {
b.start();
try {
long start = System.currentTimeMillis();
....
}
}
A better solution is to start using the higher level concepts in the java.util.concurrent library. Instead of creating a new thread, send a task to be computed by a thread pool:
ExecutorService threadPool = Executors.newFixedThreadPool(1);
Future<?> submit = threadPool.submit(() -> {
// ThreadB computation logic
});
and then specify a timeout to wait for its results:
try {
submit.get(1, TimeUnit.SECONDS);
} catch (Exception e) {
// handle timeout, interruption, exceptions
}
Note that on Android, it's not a great idea make the main thread block or wait, even if it's for only 1 second.
I have the following java code, that uses the ScheduledExecuterService. Basically, there are two important calls made in this method: 1. the integrationMonitor.Processor(...) and 2. the runIntegrationSynching() methods.
The scheduler will make sure that these methods execute according to the time interval. Recently however, I've had the problem where processing of these two methods are very long. If the user then sets the timer interval to too low, the next processing cycle will start, even before the previous one finished.
Someone here suggested I use semaphores to do the synchronization, and I did - it works for one of my test cases, but not the other one.
I am using a semaphore to prevent a new schedule cycle to start, if a previous one is still busy. How can I know when a thread finished so that I can release the semaphore?
Here is the code:
static Semaphore semaphore = new Semaphore(1);
final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleWithFixedDelay(new Runnable() {
#Override
public void run() {
try {
semaphore.acquire();
catch(InterruptedException e1) {}
runIntegrationSynching();
try {
semaphore.release();
} catch(InterruptedException e1) {}
Thread thread = new Thread(){
public void run(){
IntegrationMonitor intgrationMonitor = new IntegrationMonitor();
try {
semaphore.acquire();
} catch(InterruptedException e1) {}
intgrationMonitor.Processing(configXML, rcHost, alarmMonitorMap, blocker);
try {
semaphore.release();
} catch(InterruptedException e1) {}
if(intgrationMonitor != null){
intgrationMonitor = null;
}
}
};
LOGGER.info("Attempting to start the thread for RC " + rcHost + ". Thread ID:" + thread.getId());
thread.start();
}
},2,2,TimeUnit.MINUTES);
I want to create long-running application for performing various tasks on different threads. Each task should have one-minute timeout. Here is my implementation:
runner = new Thread(new Runnable() {
#Override
public void run() { }
// some actions here
});
runner.start();
startJoin = System.currentTimeMillis();
runner.join(TIMEOUT);
stopJoin = System.currentTimeMillis();
if ((stopJoin - startJoin) >= TIMEOUT)
throw new TimeoutException("Timeout when reading the response from process");
In general case it is working and throwing TimeoutExceptions, but sometimes it is doing nothing after even few hours. So the questions is if Thread.join is reliable on Android?
I have an idea to use Thread.wait and notify instead of that, what is the better way in your opinion?
Refer below program.
public static void main(String[] args) throws InterruptedException {
long TIMEOUT=100;
Thread runner = new Thread(new Runnable() {
#Override
public void run() {
for(;;){
System.out.println("running ");
}
}
// some actions here
});
runner.start();
long startJoin = System.currentTimeMillis();
runner.join(TIMEOUT);
long stopJoin = System.currentTimeMillis();
if ((stopJoin - startJoin) >= TIMEOUT)
try {
throw new Exception("Timeout when reading the response from process");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Running Thread");
}
This program never ends that means your logic is incorrect.
Better to use TimerTask.
I prefer doing all time base task using Timer and TimerTask. Check the following code and probably this should be useful to you:
Timer t =new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
//The task you want to perform after the timeout period
}
}, TIMEOUT);
EDIT
I am giving a try at solving your problem. I am using the code written by #amicngh as my base code and have done some modifications to it. I presume that after the TIMEOUT period you want to close the running thread. Check the following code runs fine and the explanation that follows:
public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
final long TIMEOUT=100;
final long startJoin = System.currentTimeMillis();
Thread runner = new Thread(new Runnable() {
long stopJoin;
#Override
public void run() {
try{
for(;;){
System.out.println("running ");
stopJoin = System.currentTimeMillis();
if ((stopJoin - startJoin) >= TIMEOUT){
throw new Exception();
}
}
}
catch (Exception e) {
// TODO: handle exception
}
}
// some actions here
});
runner.start();
synchronized (ThreadTest.class) {
ThreadTest.class.wait(TIMEOUT);
}
/*if ((stopJoin - startJoin) >= TIMEOUT)
try {
throw new Exception("Timeout when reading the response from process");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
System.out.println("Running Thread");
}
}
The Thread API description says that it is unsafe to destroy or stop (hence both these method has been deprecated) and one of the way to stop a thread is to throw an exception. Hence I am checking for the Timeout inside the runner thread. Now about making the Main thread wait it is done by the 2 lines of code which uses synchronized to synchronize the access to the thread.
Hope this code and explanation solves your problem.
I am trying to create a solution to treat hung threads due to memory leaks, locked resources in our applications. One of the main problems I am having is trying to simulate a hung thread to deal with it. Any sugestions?
This is what I tried, but it just doesn't seem to do the job. Any thoughts?
class KillerThread extends Thread{
public KillerThread() {
super();
}
public KillerThread(String threadName) {
super(threadName);
}
public void run (){
System.out.println("Start of KillerThread " + this.getName() );
if ( System.currentTimeMillis() % 2L == 0 ){
try {
sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
for(;;);
}
}
}
Joining on one's own thread works well for me:
Thread.currentThread().join();
try running sleep in a while loop like:
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
running a thread then tell it to sleep in an unstoppable loop, is a good idea,.
but how if you are trying to make it waiting another thread,.? make more than one thread and make them wait one each other, a deadlock condition, is that a hung to,.?
I know what you need exactly, you are testing something through stopping the executor thread. Try something like this:
private void testKillingThread() {
Object kill = new Object();
try {
synchronized (kill) {
kill.wait();
}
} catch (Exception e) {
// Auto-generated catch block
}
}
Simply enough, just create a private member
private Object lock = new Object();
then use it to wait for a notification (that will never happen, unless you use reflection...)
while (true) {
try {
synchronized (lock) {
lock.wait();
}
} cath (InterruptedException e) {
/* ignore interruption */
}
}
and you thread will hang there, uninterruptable.
Here's a quick fix I'm using for testing. Just have the thread you want to lock up call new Hanger().hang().
Remove the logging if you're not interested in seeing it. You can add throws InterruptedException (although, in fact, it never does) to the hang method so you can just replace a Thread.sleep() with a new Hanger().hang() without otherwise modifying your code.
public class Hanger {
private final static Logger log = Logger.getLogger(Hanger.class);
private long started = 0;
private final int beat = 100; // ms
/**
* Hangs a thread for the indicated time
* #param millis the amount of time to hang the thread, in milliseconds
*/
public void hang(int millis) {
started = System.currentTimeMillis();
log.debug("Hanging this thread for " + millis + " ms");
while (hung() < millis) {
try {
Thread.sleep(beat);
} catch (InterruptedException e) {
log.debug("Still hanging, will release in " + (millis - hung()) + " ms.");
}
}
log.debug("Releasing thread again after " + hung() + " ms");
}
private int hung() {
return (int)(System.currentTimeMillis() - started);
}
}
I am trying to do something conceptually simple...
We have multiple portlets loading on a Dashboard. I need to measure the load time that each takes. I have implemented a simple StopWatch class, and need to run multiple instance of it simultaneously, for each portlet, while the Dashboard is loading.
So the parameters supplied will be:
The portlet name
The element to be checked, indicating a successful load.
Here is the StopWatch class:
public class StopWatch implements Runnable {
private long startTime;
private long stopTime;
private String tElement;
private String tPortletName;
public StopWatch(String portletName,String element) {
tElement = element;
tPortletName = portletName;
}
public void start() {
startTime = System.currentTimeMillis();
}
public void stop() {
stopTime = System.currentTimeMillis();
}
public long getTime() {
return stopTime - startTime;
}
#Override
public void run() {
selenium.selectFrame(tPortletName);
StopWatch sw = new StopWatch();
sw.start();
while (selenium.isElementPresent(tElement)==false)
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
sw.stop();
long time = sw.getTime();
System.out.println(tPortletName+" load time="+time);
}
}
In the calling program,
StopWatch sw1 = new StopWatch(portlet1,element1);
StopWatch sw2 = new StopWatch(portlet2,element2);
ExecutorService threadExecutor = Executors.newFixedThreadPool(3);
threadExecutor.execute(sw1); // start task1
threadExecutor.execute(sw2); // start task2
Upon running this, I get the following exception:
com.thoughtworks.selenium.SeleniumException: ERROR Server Exception: commandHolder got filled during execution of doCommandWithoutWaitingForAReponse
Any clues on what causes this?
Most likely the reason is that you are sending commands faster then Selenium can process them.
Anyway this approach should not work since DefaulSelenium and other Selenium classes are not synchronized so if you most likely you will get deadlocks or unpredictable results.
I think you will have to test this in two steps: load dashboard, wait for first portlet, then reload dashboard and wait for second portlet. Do all of this in the main thread, something like:
private void waitForPortlet(String portletName, String element) {
long startTime = System.currentTimeMillis();
while (selenium.isElementPresent(element) == false)
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
long stopTime = System.currentTimeMillis();
System.out.println(portletName + " load time=" + (stopTime - startTime));
}
And use:
waitForPortlet(name1, element1);
selenium.refresh();
waitForPortlet(name2, element2);