I would go for an ScheduledExecutorService. Create a thread and as long as isOverloaded()
returns true re schedule the execution.
What is the best way to stop execution for few seconds in java?
-
23-09-2022 - |
Question
I am new to Java. I tried to write a program to check database status (overloaded or not).
CODE:
package com.test.service;
import java.util.LinkedList;
import java.util.List;
public class PersonImpl {
public PersonService personService;
public void InsertPersonDetails(Person person) {
if(personService.isOverLoaded()) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
//pass control to dao
}
}
}
Here I will get boolean
from isOverLoaded
. If isOverLoaded
value is yes then we should stop passing control to dao for few seconds and then check isOverLoaded
method again.
Help would be appreciated :)
Solution 2
OTHER TIPS
Your code looks work fine.
if(personService.isOverLoaded())
{
try {
Thread.sleep(5000);
//Any other code to execute after 5 min execution pause.
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
//pass control to dao
}
Thread.sleep(5000)
pause your execution for 5 sec and resume it again. If your have any code after this statement than it will executed after 5 sec of pause if not than it will execute code written after your if/else is completed.
If you want to continue check database overload status than you need to continue execute your function personService.isOverLoaded()
after every 5 sec to check your database status.
For Example :
while(personService.isOverLoaded())
{
try {
Thread.sleep(5000);
//Any other code to execute after 5 min execution pause.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//pass control to dao
As an alternative you could a java.util.concurrent.BlockingQueue to control the flow. You would start the dao as a consumer of the queue in a thread. Your InsertPersonDetails method would then push to the queue from the main thread.
Can I also point out that it is usual in java to start methods with a lowercase letter so your method would be
public void insertPersonDetails(Person person)
Your code looks ok and should work. But you need to make sure that the boolean
value passed by personService.isOverLoaded()
is volatile
.
Volatile
will make sure that value of this boolean
flag is not cached by your processing thread.
private volatile boolean flag = false;
public void overLoaded(){
flag = true; // based on some condition
}
public boolean isOverLoaded(){
return flag; // Accessed in your thread
}