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.
Related
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
I need to have a background thread that constantly does an action, sleep for X seconds and do the action etc.
Basically the run method is something like:
while(!isInterrupted()){
//do something
Thread.sleep(10);
}
My question is:
Does it make sense to use an executor in this case? Since I am not
spawning threads, is even in this case using an executor (single
threaded) better?
Additionally if I want a guarantee that the thread goes in the do
something part in exactly 10 seconds, is that possible via using
just a custom thread or more guaranteed via an executor? I mean if I have a hard limit of 10 seconds to perform an action, what can I do to achieve it? I assume that the time that the code goes back in do something may fluctuate due to scheduling etc. How could I get such a guarantee?
If you are using only a single thread which is a forever running task like yours then you can use your present logic.
But only when you have some small tasks that need to be run, then there is point in using SingleThreadPool.
How could I get such a guarantee?
There is no such guarantee from the OS side (Linux or Windows), that the thread will return from sleep at exact 10 seconds. Try increasing thread priority, but that too is not guaranteed to work.
Your logic should not be dependent on such hard timings IMO.
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).
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.
In a program (Java) I'm making I need to check for a specific pin in the parallel port. Whenever that pin goes from logical 0 to 1 (a positive edge clock) I have to read the data on the port and save it. This happens about every 10ms but can vary a little.
To do this I made a separate thread with a while loop that is constantly checking the port, but this makes the processor go nuts and I know it's because of the while loop. My question is, how can I constantly scan the port without using a processor intensive while loop? The program doesn't know precisely when a pin change will happen, only that it happens around every 10ms.
Fire a thread which is scheduled to execute the given Runnable at a fixed rate. You can use Timer#scheduleAtFixedRate() or ScheduledExecutorService#scheduleAtFixedRate() for this. The last one is preferred.
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new PortScanner(), 0, 10, TimeUnit.MILLISECONDS); // Run every 10 ms.
Where PortScanner can look like this:
public class PortScanner implements Runnable {
#Override
public void run() {
// Scan port here.
}
}
Don't forget to call scheduler.shutdown() at the moment your application exits, else the thread may hang.
There might be a better solution, but worst case you could just Thread.sleep for 1-2ms every iteration of the while loop.
It is really tricky to catch hardware interrupts when your code is not running as a part of operating system. What you can do is to put Thread.Sleep ( 5 ). This will sleep for 10 milliseconds, and will let the other threads run or just keep CPU idle and cool. Having 5 ms delay should be enough to ensure won't miss any clock ticks.
This would work when your clock is alternating between 10 ms high and 10 ms low. For other patterns you have to adjust the parameter accordingly.