How to determine the remaining wait time of thread in Java - java

I understand that there is no specific method in the Thread class that allows a program to check how many remaining time a thread has before it wakes up. But in case you need such feature, how would you implement it?
For example I have:
Thread A - at a certain condition it waits for an amount of time.
Thread B - doesn't know that thread A is set to wait for an amount of time.
Questions:
1. Is there a way for thead B to determine how many millis the thread A is set to wait?
2. How about determining how much time is remaining before the wait expires?
3. Another Thread C found that the System clock has changed, is there a way for it to determine the remaining time based on the new system clock?
Thanks
------- Edit -----
What I actually want to accomplish is to have a process scheduled to run at a specific time. I do not want to use the TimerTask for some reason so I created a Thread that will wait by (FutureDate - CurrentDate). I want to interrupt this waiting IF the system's date and time has changed (New.System.Date). Now if the (FutureDate - New.System.Date) is not so much different with (FutureDate - OldSystemDate) say just a few seconds, I wouldn't want to interrup the waiting. But if huge like a few minutes then I will have to reset the waiting to another (FutureDate - New.System.Date).

Related

How to capture elapsed time of a running java process to raise intermediate alerts

I have a java process which could either complete sooner or take longer time based on the volume of data its processing. However I need a way to capture the elapsed time after certain time continuously and need to log an alert message concurrently without interrupting the main process. I have explored Future option with ExecutorService but it would terminate the process after the set timeout and raises Timeout exception. Please suggest if you have any solution to achieve this requirement.
just some hints:
you need to have 2 separate threads: one for main logic and one for checking the progress
the thread that checks the progress should be able to know if the main thread has finished or not (the simplest solution volatile boolean flag)
the thread that checks the progress can be invoked by timer with some period

Why yield is needed as any thread might be moving to ready state even without calling yield method

I was reading about yield. It is being told that if a thread is running long and if another thread who is going to run for short time need to wait for long running thread to finish its processing. But my question is as per thread scheduler, no thread will run till its completion in one go. it has to oscillate between running and ready states. so will be the case with long running thread. eventually it will move from running to ready after some time and then will resume its works and this cycle will go on till it completes its job. then what is the role of yield? Is it just a voluntary way of moving to ready state to see if anyone need process time ?
Below is the information from https://www.geeksforgeeks.org/java-concurrency-yield-sleep-and-join-methods/ which could not clear my doubt.
yield(): Suppose there are three threads t1, t2, and t3. Thread t1 gets the processor and starts its execution and thread t2 and t3 are in Ready/Runnable state. Completion time for thread t1 is 5 hour and completion time for t2 is 5 minutes. Since t1 will complete its execution after 5 hours, t2 has to wait for 5 hours to just finish 5 minutes job. In such scenarios where one thread is taking too much time to complete its execution, we need a way to prevent execution of a thread in between if something important is pending. yeild() helps us in doing so.
yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should run. Otherwise, the current thread will continue to run.
yield() says to the Java runtime "You may now proceed with another thread". With current operating systems (like Unix or Windwos) which have native threads and preemptive multitasking, a long running thread will be eventually paused for some time and other threads will be executing. With yield() this will possibly happen earlier.
On current environments this functionality is not important in most cases. It is especially useful, if you have only cooperaive multitasking, when there is effectively only one thread and another process can only execute when the current process explictly allows to be paused by calling yield().

What does thread's idle time mean in Java?

What is the meaning of idle time with respect to threads in Java?
I'm reading Java The Complete Reference 8th edition's and
it says something like this:
...One thread can pause without stopping other parts of your program.
For example, the idle time created when a thread reads data from a
network or waits for user input can be utilized elsewhere...
In this case, it means the thread's state is WAITING or TIMED_WAITING, which means
A thread in the waiting state is waiting for another thread to perform
a particular action.
Imagine there is only one CPU. There are two things the user wants to do.
1) Download song and play it (lets say song download takes 10 sec to get network connection download it for 5 seconds, and plays for 60 seconds).
2) Copy another file from one folder to another (lets say file copy takes 3 seconds).
In this case, if there is only one thread, then that thread waits for 10 sec to get connection, and 5 sec to download, play the song for 60 seconds and then copy another file for 3 seconds.
In all this, when the thread is waiting for 10 sec to obtain a network connection, nothing is being done until it actually gets the connection, and is just idle doing nothing. Now, when a thread is idle, the CPU is not being used. Now, when this is the case, should there be another thread, then that thread could have been used for the 3 second file copy when the first thread is waiting for 10 sec in order to obtain a network connection.
In the first case, 10 sec is called idle time
A thread can be in 2 states: idle state or working state. A working thread occupies a CPU and executes some program. An idle thread does not occupy a CPU, only core memory. Any idle thread is waiting for some event, and so is linked to corresponding event queue.
For example, a monitor has 2 queues: one for threads trying to execute synchronized statement, and the other for threads who invoked Object.wait() method.
When the event happens, one or all threads are taken from the event queue and put to the processor queue, where they wait a CPU to become free. When a CPU becomes free, it takes next thread from the processor queue and starts to execute its code from the place it asked for some event, and got to the queue.
Actual states of JVM threads differ from this simplified picture.
I can try to explain it further with an example that contains a series of events.
A simple program reads user input, writes it to database, and reports status back to the user.
Sequence of operations:
Read user IO [thread A]
Process it and write to database [thread B]
Reports status back to user [thread A]
In above thread A will pause after sequence 1 until it is unblock by thread B. So while sequence 2 is going on thread A is in idle state.

How to properly wait for next second tick

I'm working on real-time system. Which requires balancing load per second. So when computing is done I've to put a thread to sleep state till next second right now I'm doing this by:
Thread.sleep(((1000 - (Calendar.getInstance().getTimeInMillis() % 1000))));
but it looks really ugly for me. Do you have any tip to improve this?
Instead of having the threads all sleep some amount of time, have the threads wait on a signal from a manager thread.
This way, only one thread needs to keep track of ticks, and the others just do work, then wait for a signal to do more work.

caching db table at a particular time?

I have to cache some db records some time period.
For example i am assuming huge traffic on my website at 4 pm today.I will cache the login table at around 3.50.Because i know that users will come at this time.
How can i go about it in java?I am thinking is running a thread at specific interval and then
running it at every 1 hr to check if i need something to be cached
Is the thread guaranteed to run?
class Mthread extends Thread{
run(){
//update cache
}
}
you may take a look on java Cron. I guess this should solve your problem.
http://www.sauronsoftware.it/projects/cron4j/
Cron jobs are used to trigger some action at particular time and is highly configurable like you can configure it to work daily at 3:50 PM.
Hopefully it should solve your problem
You can implement your run() method using a while loop that loops indefinitely. At the end of every iteration of the loop, calculate the number of milliseconds for your thread to sleep until the next update time (perhaps set a maximum sleep time if you want it to wake up periodically). The thread is guaranteed to run when you want it to, provided the following:
You tell it exactly how long it needs to sleep or wait until the next cache update time.
Your thread doesn't get interrupted before you want it to.
No exceptions cause your thread's run() method to return prematurely.
Your thread doesn't cause some weird error, like an OutOfMemoryError, to occur.

Categories

Resources