How to properly wait for next second tick - java

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.

Related

How can I find out how much time was left to sleep after thread was interrupted?

I have a thread, on which i am calling sleep() for a specific amount of time. If the thread is interrupted, I need a way to know how much time was left. Is there a built-in way to do this?
P.S. I have a strong suspicion that this may be an XY problem. (i.e. I'm thinking about this completely wrong)
When starting the sleep, determine the end of sleep first. If the sleep is interrupted and should be resumed, sleep for originalEndTime - now ms.
It's so not clear what exactly you're trying to do though tasks, you're probably right about the XY.

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.

CPU consumption when thread is sleeping using Thread.sleep

I have a server program which polls a database for new requests , I want this polling to be done at 1 minute intervals so , I've set up a Thread.sleep() in the program while loop.
The problem is that whenever this program is supposed to "sleep" the CPU consumption goes up drastically (viz. about 25 - 30%).
Paradoxically, when the program is not dormant and is busy processing requests , the CPU consumption drops to 0.4%.
I read online and found out that there are performance hits associated with thread.sleep, but I could not find any viable alternative (Thread.wait requires notification on an object, something which I feel is useless in my scenario)
The main loop (when there are no new requests) doesn't do anything, here is a skeleton of all that is being done when the CPU consumption is 25%
-> poll
-> No new records ?
-> Sleep
->repeat
Check what the CPU consumption is for individual CPU cores. If you are using a 4 core machine, maybe one thread is going rogue and is eating up once core (25%). This usually happens when the thread is in a tight loop.
You could use Thread.wait with a timeout (which indeed the Timer class does), but my bet is that it won't make any difference. Both Thread.sleep and Thread.wait changes the threads' state to not runnable. Although it depends on your JVM implementation etc., the thread shouldn't consume that much CPU in such situation. So my bet is that there is some bug at work.
Another thing you can do is taking a thread dump and see what the thread is doing when this happens. Use kill -3 on a Linux box, or use ctrl+break on the java console window if you are using Windows. Then, examine the thread dump that is dumped to the standard output. Then you can be sure if the thread was actually sleeping or was doing something else.
As many people pointed out, Thread.sleep should and actually does help with dropping the CPU usage drastically.
I omitted certain facts from my original question as I thought they were not relevant.
The main thread was the producer, there was another thread running asynchronously which was the consumer. It turns out that the "sleep" on this thread was inside some weird condition that wasn't getting triggered properly. So the loop on that thread was never sleeping.
Once the sleep thing was eliminated I went ahead and analyzed it closely to realize the problem.

How to determine the remaining wait time of thread in 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).

ThreadPoolExecutor - ArrayBlockingQueue ... to wait before it removes an element form the Queue

I am trying to Tune a thread which does the following:
A thread pool with just 1 thread [CorePoolSize =0, maxPoolSize = 1]
The Queue used is a ArrayBlockingQueue
Quesize = 20
BackGround:
The thread tries to read a request and perform an operation on it.
HOWEVER, eventually the requests have increased so much that the thread is always busy and consume 1 CPU which makes it a resource hog.
What I want to do it , instead sample the requests at intervals and process them . Other requests can be safely ignored.
What I would have to do is put a sleep in "operation" function so that for each task the thread sleeps for sometime and releases the CPU.
Quesiton:
However , I was wondering if there is a way to use a queue which basically itself sleeps for sometime before it reads the next element. This would be ideal since sleeping a task in the middle of execution and keeping the execution incomplete just doesn't sound the best to me.
Please let me know if you have any other suggestions as well for the tasks
Thanks.
Edit:
I have added a follow-up question here
corrected the maxpool size to be 1 [written in a haste] .. thanks tim for pointing it out.
No, you can't make the thread sleep while it's in the pool. If there's a task in the queue, it will be executed.
Pausing within a queued task is the only way to force the thread to be idle in spite of queued tasks. Now, the "sleep" doesn't have to be in the same task as the "work"—you could queue a separate rest task after each real task, which might make for a cleaner implementation. More importantly, if the work is a Callable that returns a result, separating into two tasks will allow you to obtain the result as soon as possible.
As a refinement, rather than sleeping for a fixed interval between every task, you could "throttle" execution to a specified rate. This would allow you to avoid waiting unnecessarily between tasks, yet avoid executing too many tasks within a specified time interval. You can read another answer of mine for a simple way to implement this with a DelayQueue.
You could subclass ThreadPool and override beforeExecute to sleep for some time:
#Overrides
protected void beforeExecute(Thread t,
Runnable r){
try{
Thread.sleep( millis); // will sleep the correct thread, see JavaDoc
}
catch (InterruptedException e){}
}
But see AngerClown's comment about artificially slowing down the queue probably not being a good idea.
This might not work for you, but you could try setting the executor's thread priority to low.
Essentially, create the ThreadPoolExecutor with a custom ThreadFactory. Have the ThreadFactory.newThread() method return Threads with a priority of Thread.MIN_PRIORITY. This will cause the executor service you use to only be scheduled if there is an available core to run it.
The implication: On a system that strictly uses time slicing, you will only be given a time slice to execute if there is no other Thread in the entire program with a greater priority asking to be scheduled. Depending on how busy your application really is, you might get scheduled every once in awhile, or you might not be scheduled at all.
The reason the thread is consuming 100% CPU is because it is given more work than it can process. Adding a delay between tasks is not going to fix this problem. It is just make things worse.
Instead you should look at WHY your tasks are consuming so much CPU e.g. with a profiler and change them so that consume less CPU until you find that your thread can keep up and it no longer consumes 100% cpu.

Categories

Resources