Executing statement after 10 seconds - java

I am running my java listener codes.
What happens is that my server will send some command to the client.
Thereafter I want to wait and see in 10s if there is no reply, then keep retrying for 5 times.
Below is what I do.
//Select code from the db with the codeID, codeText.
//send the code to the client.
long t= System.currentTimeMillis();
long end = t+10000;
while(System.currentTimeMillis() < end) {
}
//Select from db to check if codeupdated.
If updated dont do anything else I need to repeat the above pause ?
I having issue to repeat it for 5 times?

There is no guarantee for your construct to last exactly 10 seconds, and it's very costly in terms of performance.
Just use Thread.sleep.
for (int i = 0; i < 5; i++) {
// TODO your request here
boolean success = true; // TODO change to whatever outcome of your
// request
if (success) {
break;
}
else {
try {
Thread.sleep(10000l);
}
catch (InterruptedException ie) {
// TODO handle interruptions if applicable
}
}
}

Use
Thread.sleep(10*1000); //sleep 10 seconds.

You should use Thread.sleep() to pause execution
It's well explained here :
http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html

Related

java long term thread

I am currently facing a challenge with executing following thread in my webapplication:
return new Runnable() {
#Override
public void run() {
long lastHeartBeat = -1;
while (true) {
if (isFullAbortRequested()) {
break;
}
if (lastHeartBeat == -1 || lastHeartBeat + 1000 * 60 < new Date().getTime()) {
// once every x minutes send a "i'm still alive!"
DEFAULT_LOGGER.info("still alive!");
lastHeartBeat = new Date().getTime();
}
//DO SOMETHING THAT TAKES 1 MIN
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
DEFAULT_LOGGER.error("CACHE REFRESH SERVICE DOWN");
}
}
}
};
The problem with this one, is that after some days it just stops (without any known reason). Is this a "expected behaviour" on such "while(true) sleep" threads that they might be closed by OS (?) or anything else?
What would be a durable solution for this "check every second if you have to do something, and if yes, do it (can take 1 min). then wait a second before next check"? The actions in "DO SOMETHING" should never parallize or overlap, so they should be blocking for this thread.
Thank you in advance!

kill process after some time in java

i want to terminate some process after some time if that process will not responded
i used this code but i am not able to achive the same
long start = System.currentTimeMillis(); long end = start +60000;
1 while (System.currentTimeMillis() < end)
2 {
3 Connection.execute(function); // execute
4 break; // break if response came
5 }
6 if(System.currentTimeMillis() > end)
7 {
8 close connection; // close connection if line no 3 will not responded
9 }
kindly help me on the same
As the call Connection.execute() is blocking, so main thread will be blocked until it executes, SO in that case if we want to close the connection when the main thread is blocked , we have to close connection in some other thread. May be we can use Timer & TimerTask in this case. I tried to write some code as below, May be you can some thing like that.
Timer timer = new Timer();
while (System.currentTimeMillis() < end) { //In any case, this loop runs for only one time, then we can replace it with IF condition
CloseConnectionTask task = new CloseConnectionTask(Connection);
timer.schedule(task, end); // Task will be excuted after the delay by "end" milliseconds
Connection.execute(function); // execute
task.cancel(); //If the excute() call returns within time ie. "end" milliseconds, then timerTask will not get executed.
break; // break if response came//
}
timer.cancel(); // If you have no more scheduling tasks, then timer thread should be stopped.
Below is TimerTask implementation:
class CloseConnectionTask extends TimerTask {
private Connection con;
public CloseConnectionTask(Connection con) {
this.con = con;
}
#Override
public void run() {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Note: I have one more thing to say, In your while loop, If the call to Connection.execute() successful, then you break from the loop. So what I have observed, In any case your loop is executing only once, If this is the case, then you should use IF(again its what I have seen in the provided code, you requirement may be different). Hope it may help you. If you have other thoughts on this, please share. My answer is based on this link, Good info. is there.
this way it will not help
i think you should implement thread to achieve that

overload in step find element

I have selenium java code testing some site in ff 41 and selenium 2.48. Last step of my code is findElement (timeout 30 sec). I don't have any error and my test does not fail. But I see overload in this step, its duration is 88 - 150 sec.
Any idea why my test does not fail after 30 sec?
Here is my last step code
errorMessage = "";
boolean flag23 = false;
for (int k = 0; k < 30; k++)
{
try
{
List<WebElement> element23 = findElements("print-confirmation");// "//a[#class='print-confirmation']");
if (element23.size() != 0)
{
flag23 = true;
break;
}
}
catch (Exception e)
{
pause(1000);
}
}
assertTrue(flag23); // new WebDriverWait(driver,
// 30).until(ExpectedConditions.presenceOfElementLocated(By.id("//a[#class='print-confirmation']")));
writer.append("\ntest89028:23 OK " + getRunTime(System.currentTimeMillis() - startTime));
startTime = System.currentTimeMillis();
If I get it right, you call findElements 30 times and you pause 1s after each iteration if you do not find your element yet. So you need worst case 30s only for pausing, plus time for the whole loop and especially for findElements. So your recorded time is more than 30s, since you record the whole code block execution. I don't know if I got it right and this might help you.
I'm not sure what is in the findElements() function... maybe a wait or sleep? Something in there is likely magnifying the wait time or you have an implicitWait() set. I would rewrite this block of code like this... (and remove any implicitWait()).
boolean flag23 = false;
try
{
new WebDriverWait(driver, 30).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//a[#class='print-confirmation']")));
flag23 = true;
}
catch (TimeoutException e)
{
System.out.println("Element not found due to TimeoutException");
}
assertTrue(flag23);
I think it's easier to read and is more controlled. You should not mix implicit and explicit waits or you will get weird behaviors (likely similar to this).
http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp#explicit-and-implicit-waits
WARNING: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example setting an implicit wait of 10s and an explicit wait of 15 seconds, could cause a timeout to occur after 20 seconds.

Java: How to distinguish between spurious wakeup and timeout in wait()

Here is a case where a thread is waiting for notify() or a timeout. Here a while loop is added to handle spurious wake up.
boolean dosleep = true;
while (dosleep){
try {
wait(2000);
/**
* Write some code here so that
* if it is spurious wakeup, go back and sleep.
* or if it is timeout, get out of the loop.
*/
} catch (InterruptedException e) {
e.printStackTrace();
}
}
In this case how can I distinguish between a spurious wake up and time out? If it is a spurious wake up, i need to go back and wait. And if it is a timeout, i need to get out of the loop.
I can easily identify the case of notify(), because i will be setting the dosleep variable to false while notify() call.
EDIT: i am using 1.4 java version, due to embedded project requirement. I cannot use Condition as it is available only post 1.5.
Thanks in advance.
You could do this:
boolean dosleep = true;
long endTime = System.currentTimeMillis() + 2000;
while (dosleep) {
try {
long sleepTime = endTime - System.currentTimeMillis();
if (sleepTime <= 0) {
dosleep = false;
} else {
wait(sleepTime);
}
} catch ...
}
That should work fine in Java 1.4, and it will ensure that your thread sleeps for at least 2000ms.
You need to keep track of your timeout if you want to distinguish the two cases.
long timeout = 2000;
long timeoutExpires = System.currentTimeMillis() + timeout;
while(dosleep) {
wait(timeout);
if(System.currentTimeMillis() >= timeoutExpires) {
// Get out of loop
break;
}
}
That said, denis's recommendation of using the Condition class is the better way to do this.
I believe Locks and Condition will better fit your need in this case. Please check the javadocs for Condition.awaitUntil() - it has an example of usage

How to handle output of Threads correctly? java

I try to handle the output of different runnables wihtin another thread. First I add all runnables to a set and try to trigger their progress, which is saved into a map toether with the category. The category is the identifier for each runnable. There can exist only one runnable per category.
After that I try to write out the output in a progress bar on the stdout. But it is empty (0%) everytime. The strange thing is, when I am debugging in Eclipse, step by step, the progress bar seems to work correctly. I cannot find the problem, maybe it's some timing problem, or something else.
Can some tell what I am doing wrong?
If someone knows a better way of handling the output of different Threads, please let me know. I am would be happy, definitely.
Thanks in advance for your help.
This is my WriterThread:
public class WriterT extends Thread {
Set<Runnable> my_runnables = new HashSet<Runnable>();
Map<String, Integer> all_runnable_progress = new HashMap<String, Integer>();
public WriterT() {
}
public void add(Runnable r) {
my_runnables.add(r);
}
public void run() {
if(!my_runnables.isEmpty()) {
int progress = 0;
while(true) {
for(Runnable r : my_runnables) {
if(r instanceof Verify_TestRun) {
Verify_TestRun run = (Verify_TestRun)r;
progress = run.get_progress();
all_runnable_progress.put(run.get_category(), progress);
}
}
if(progress <= 100) {
print_progress();
} else {
break;
}
try {
Thread.sleep(150);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void print_progress() {
StringBuilder str_builder = new StringBuilder();
for(String cat : all_runnable_progress.keySet()) {
int percent = all_runnable_progress.get(cat);
str_builder.append(cat + "\t[");
for(int i = 0; i < 25; i++){
if( i < (percent/4)){
str_builder.append("=");
}else{
str_builder.append(" ");
}
}
str_builder.append("] " + percent + "%" + "\t");
}
System.out.print("\r" + str_builder.toString());
}
}
Updated answer after new information
So if I understand you correctly, you want to go over each test run you are tracking, see if any of them is still running i.e. the progress is less than 100 and print the progress as long as they're not all finished.
First, you need to consider what Stephen C said in his answer - you (probably) want to sum up the progress values of each of the test runs. Then, check if the sum comes out to less than 100 for each test run. If it does, at least 1 test run is still in progress and you print progress and stay in your loop. If you find that your sum comes out to exactly 100 for each test run, then you're all done. You print progress one final time to update the output to reflect 100% for each and then break from the loop.
Here is my suggested implementation that makes minor changes to your code:
public void run() {
if(!my_runnables.isEmpty()) {
int progress = 0;
while(true) {
for(Runnable r : my_runnables) {
if(r instanceof Verify_TestRun) {
Verify_TestRun run = (Verify_TestRun)r;
//change #1 - sum up the progress value of each test
progress += run.get_progress();
all_runnable_progress.put(run.get_category(), progress);
}
}
//change #2 - break when all done
if(progress < (100 * my_runnables.size()) ) {
//check if tests are still running i.e. there are test runs with progress < 100
print_progress();
} else {
//otherwise print one last status (to update all status' to 100%) before stopping the loop
print_progress();
break;
}
try {
Thread.sleep(150);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Shouldn't progress be checked within the for loop? What you're doing right now is iterating over all your Runnables and setting progress to the progress value and adding it to the map. But then you immediately move on to the next Runnable. The net result is that the value of progress once you leave the loop is the value of the last Runnable you handled.
I think that this might be the problem line:
progress = run.get_progress();
Given the context, progress will end up as the last value returned by a Verify_RunTest, but I suspect you mean it to be the sum of the values.
(BTW - Verify_RunTest is bad style. It should be VerifyRunTest.)

Categories

Resources