Java - Wait for something to be true - java

I am trying to make a program that runs in the background, and when it hits a certain time a reminder pops up on the computer.
int looplol = 2;
while(looplol != 1){
if(usertime.equals(time)){
JOptionPane.showMessageDialog(null, usertext);
looplol = 1;
}
I am trying to make it so it keeps running the program until usertime = time, then it will display the message the user wants and stop the program. This code up here isn't working, does anyone know how I can do this

This code will make a CPU core spin at 100% until the condition is reached.
If you can work out how long it is between the current time and "user time" (in milliseconds), why not just use Thread.sleep(ms)?
long userTime = <some time in the future>;
long sleepTime = System.currentTimeMillis() - userTime;
try {
Thread.sleep(sleepTime);
} catch(InterruptedException ex) {
// Shouldn't happen
}

You could simply use Thread.sleep():
private void waitUntilSystemTimeMillis(long stopTime) {
long sleepDuration = stopTime - System.currentTimeMillis();
if (sleepDuration > 0) {
try {
Thread.sleep(sleepDuration);
}
catch(InterruptedException e) {
throw new RuntimException(e);
}
}
}
And then do:
waitUntilSystemTimeMillis(time);
JOptionPane.showMessageDialog(null, usertext);
See also: https://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html

Java util package has a Timer... there you can define an object and when given, invoke a method after a delay...
You can use: Timer.schedule for doing something ONCE after a delay
Timer t = new Timer("--", true);
t.schedule(new TimerTask() {
#Override
public void run() {
JOptionPane.showMessageDialog(null, "usertext");
}
}, 5000L);

Related

java thread.sleep() take longer time after display sleep on MacOS

The target is to make current thread sleep some time, range from a few hundred milliseconds to a few seconds. The program runs normally when display is on. But after display go to sleep mode ( On MacOS, display could go to sleep after some system idle time), the Thread.sleep() would take much longer time to return. I.g.,
Thread.sleep(5000); // to sleep 5 sec, but actually it take 30+ seconds to return.
It seems like the cpu frequency has been downscale, but java jre code did not follow the changes. Tested on MacOS 10.12 + Java 8.
Question: How to make the thread sleep code to overcome this issue?
Sample Code: both cannot work on display sleep case.
public static void threadsleep(long milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException ex) {
Logger.getLogger(FetchDailyOptions.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void threadsleep(long milliseconds) {
try {
if (milliseconds < 100) {
Thread.sleep(milliseconds);
return;
}
long targetMilli = System.currentTimeMillis() + milliseconds;
for (;;) {
Thread.sleep(100); // wait 100 milliseconds
if (System.currentTimeMillis() > targetMilli) {
return;
}
}
}
catch (InterruptedException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
}
}

Breaking out of a while loop if the process takes more than a specified amount of time in java

I'm reading a server log file after an event is performed on the UI. I have a while loop which waits for certain conditions to match and then returns that line of the log. Sometimes, however, there's a case where an event occurs before the code looks at the log and cannot get the new line. This causes the while loop to just hang and this hangs until another event occurs with the provided conditions. This is problematic for obvious reasons. Is there a way to break out of the while loop after a few seconds no matter what the case maybe? Following is my code
public String method(String, a, String b, String c) {
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(a + "\n" + b);
channel.connect();
fromServer = new BufferedReader (new InputStreamReader(channel.getInputStream()));
String time = methodToFireAnEventInUI();
Thread.sleep(2000);
String x = null;
while (true){
x = fromServer.readLine();
if(!x.equals(null) && x.contains(c) && x.contains(time)){
break;
}
}
msg = x.toString();
}catch (Exception e){
e.printStackTrace();
}
closeConnection();
return msg;
}
If you look at the above code, it hangs right at "x = fromServer.readline();" and just doesn't go anywhere, and that is where I want the logic for it to wait for an x amount of time and just abort the loop after that.
My attempt of "thread.sleep" ahead of the while loop doesn't work either.
You can put this logic in a separate thread and use a while like this:
class TestThread extends Thread {
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
method();
}
}
public void method() {
try {
// this method hangs. You can replace it with your method
while (true) {
sleep(100);
}
} catch (Exception e) {
System.out.println("Thread is interrupted");
}
}
}
After that you can interrupt this thread if it takes longer than some time frame like this:
public static void main(String[] args) throws Exception {
TestThread t1 = new TestThread();
long startTime = System.currentTimeMillis();
t1.start();
long currentTime = System.currentTimeMillis();
while (currentTime - startTime < 5000) { // you can decide the desired interval
sleep(1000); // sleep some time
currentTime = System.currentTimeMillis();
System.out.println(currentTime); //print this to ensure that the program is still running
}
t1.interrupt(); //interrupt the thread
}
How about simply:
long timeOut = System.currentTimeMillis() + 5000; // change the value to what ever(millis)
while(System.currentTimeMillis() < timeOut){
// do whatever
}
As your while loop blocks at "x = fromServer.readline();" you can just share the reader instance to another thread and make that thread close the reader after timeout. This will cause your readLine to throw exception which you can handle and proceed.
Find answer here:
How do I measure time elapsed in Java?
Try the approach below:
long startTime = System.nanoTime(); //fetch starting time
while(true ||(System.nanoTime()-startTime)<200000)
{
// do something
}

How i can measure time of thread pool in java?

I have used two different approach to measure time of threads but result are not matching
**Public void Main()**
{
Timer timer = new Timer();
int timetotal;
timer.start();
int numberOfThreads=5;
ExecutorService pool= Executors.newFixedThreadPool(numberOfThreads);
List<Future<Boolean>> futureList = new ArrayList<Future<Boolean>>();
Set<ReadProcess_MongoDB> callList = new HashSet<ReadProcess_MongoDB>();
CompletionService<ReadProcess_MongoDB> taskCompletionService;
taskCompletionService = new ExecutorCompletionService<ReadProcess_MongoDB>(pool);
Collection<Callable<ReadProcess_MongoDB>> list;
list = new LinkedList<Callable<ReadProcess_MongoDB>>();
for(int i=0;i<numberOfThreads;i++)
list.add((Callable<ReadProcess_MongoDB>) new ReadProcess_MongoDB(i));
try {
for (Callable<ReadProcess_MongoDB> callable : list) {
taskCompletionService.submit(callable);
}
for (int i = 0; i < list.size(); i++) {
Future<ReadProcess_MongoDB> result = taskCompletionService.take();
}
} catch (InterruptedException e) {
// no real error handling. Don't do this in production!
e.printStackTrace();
} catch (ExecutionException e) {
// no real error handling. Don't do this in production!
e.printStackTrace();
}
finally {
pool.shutdown();
System.out.println("Done :)");
timer.stop();
System.out.println("Total consumed Time"+ timer.elapsed());
}
Other time I put in Call method()
**public String call()**
{
Timer timer = new Timer();
int timetotal;
timer.start();
DBCursor cursor = coll.find(whereQuery);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(ReadProcess_MongoDB.class.getName()).log(Level.SEVERE, null, ex);
}
timer.stop();
usedTimeForQueryProcess = timer.elapsed();
System.out.println("Thread Number="+this.threadNumber+ " MongoDB_readQuery used time "+usedTimeForQueryProcess);
System.out.println("runing.....");
return Objects.toString(usedTimeForQueryProcess);
}
In call Function, system print time of every thread and in Main function only display totaltime.Here I try check manually ,but both time are not matching .But bigger problem is Main function show less time than total time of all threads(Call function).
I have also tried to return used time from Call function But it is also create problem convert to long (especially runtime problem ).
Time of Both function
Main function time =289
Call function time=510(5 thread).
Would please somebody expain why this happening and how i can make right measurement ?
The Main time is lower than the total of each of your jobs because they are running in parallel. If you reduce your thread pool size down to 1 then you will the numbers be more like what you expect.
This is one of the benefits of doing multithreaded programming, getting more work done in less time than if it were done sequentially.

java code to wait for parallel code to finish

I m having a server code to process an image.
Now there are n number of requests which tries to execute the code which results in OutOfMemory error or the server to hang and the server goes to not responding state.
To stop the code from executing at once all the requests I m limiting to execute the code one at a time using the below method where i have a variable
if the variable is 10 then wait for the variable to come at 0
if at 0 then set it to 10 then execute the code
run the code and finally set i to 0
The code here -
static newa.Counter cn;
public int getCounta() {
return cn.getCount();
}
public void setCounta(int i) {
cn = new newa.Counter();
cn.setCount(i);
}
at the function i m doing this -
public BufferedImage getScaledImage(byte[] imageBytes)
{
int i=0;
Boolean b = false;
BufferedImage scaledImage = null;
newa.NewClass1 sc = new newa.NewClass1();
try {
sc.getCounta();
} catch (NullPointerException ne) {
sc.setCounta(0);
}
i = sc.getCounta();
if(i==0)
{
sc.setCounta(10);
b = true;
}
else
{
while( b == false)
{
try
{
Thread.sleep(2000);
i = sc.getCounta();
if( i==0)
{
sc.setCounta(10);
b = true;
System.out.println("Out of Loop");
}
} catch (InterruptedException ex) {
System.out.println("getScaledImage Thread exception: " + ex);
}
}
}
..... execute further code
try { } catch { } finally { sc.setCounta(0); }
}
Is there any way I can have this simplified using the Runnable interface or something as I don't know how to do multi-threading.
Forget about the counter and use a synchronized method. Changed your method head to this:
public synchronized BufferedImage getScaledImage(byte[] imageBytes)
This lets all the threads entering the method wait until no other thread is executing the method.
If you want only a small number of threads doing the processing you can use Executor framework to have a thread pool of 10 threads. This will ensure that at one time maximum of 10 threads will be processing the requests.

Chatbot delay between saying something and getting answer

So in my chatbot program, I want to make it so it waits about 2 seconds after I said something before it answers. I tried the sleep method but that makes what I said be delayed as well...
I tried to find something on the wait method but I can't seem to find out how it works so here's my piece of code for answering.
I want it to wait 2 seconds after doing the "addText(ft.format(dNow) + " |-->You:\t"+quote);" part and then write the answer of the chatbot
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("hh:mm:ss");
input.setEditable(false);
//-----grab quote-----------
String quote=input.getText();
input.setText("");
addText(ft.format(dNow) + " |-->You:\t"+quote);
quote.trim();
while(
quote.charAt(quote.length()-1)=='!' ||
quote.charAt(quote.length()-1)=='.' ||
quote.charAt(quote.length()-1)=='?'
)
{
quote=quote.substring(0,quote.length()-1);
}
quote=quote.trim();
byte response=0;
//-----check for matches----
int j=0;//which group we're checking
while(response==0){
if(inArray(quote.toLowerCase(),chatBot[j*2]))
{
response=2;
int r=(int)Math.floor(Math.random()*chatBot[(j*2)+1].length);
addText("\n" + ft.format(dNow) + " |-->Miku\t"+chatBot[(j*2)+1][r]);
if(j*2==0){
try (BufferedReader br = new BufferedReader(new FileReader("mikuname.txt"))) {
String name;
while ((name = br.readLine()) != null) {
addText(name +"!");
}
} catch (IOException e1) {
// Do something with the IO problem that occurred while reading the file
}
}
}
j++;
if(j*2==chatBot.length-1 && response==0)
{
response=1;
}
}
Thread.sleep() would only work if you had the response processed on a different thread. Because you don't, you'll need to take a different approach.
Use the ScheduledExecutorService object to schedule a task for two seconds in the future.
Example
// Create the service object.
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
// Schedule the task for the next 5 seconds.
ScheduledFuture scheduledFuture =
scheduledExecutorService.schedule(new Callable() {
public Object call() throws Exception {
System.out.println("Executed!");
return "Called!";
}
},
5,
TimeUnit.SECONDS);
Code taken from here.
You could schedule whatever you want to send out using a Timer and a TimerTask. Here's an example

Categories

Resources