Preferred way of waiting on two ExecutorServices? - java

I have two ExecutorServices, one to hold producers and the other one to hold consumers. I'm using the awaitTermination method, which is blocking and needs a timeout parameter. But I want to wait on both ExecutorServices with the same timeout. As the awaitTermination call is blocking, I can't do:
this.producersExecutorService.awaitTermination(4, TimeUnit.HOURS);
this.consumersExecutorService.awaitTermination(4, TimeUnit.HOURS);
Because that would, eventually, wait for a total of 8 hours. What should I do?

If you're waiting for both of them, just await either of them with a timeout of 4 hours, then await the other one with however much time is remaining. How you determine that is up to you - I'd probably work out the desired end time based on the current time before the first call to awaitTermination, and then work out the remaining time based on the difference between that and the current time.
It's not clear from the documentation what happens if you pass in a negative time - you should probably investigate that, and potentially take precautions (e.g. if the first call finishes at exactly the timeout, and then you end up computing the second timeout a millisecond later).

Related

How long does Timer.schedule schedule for when delay is 0?

In Timer.schedule(TimerTask task, long delay), it says it will throw if delay is negative, but doesn't say anything about if delay is zero. What will happen? I tried on openjdk and it ran instantly. Is this behavior specified somewhere else, or is it undefined (e.g it means infinite on other implementations, or some implementations will do infinite sometimes and instant sometimes)?
From the Java SE7 documentation:
If delay is less than or equal to zero, the timer fires as soon as it is started
So the result you got is the expected behavior.
I believe a Timer in java is a Thread with a task queue. Items are ordered in the task queue by when they are supposed to fire. Tasks with a delay of 0 are supposed to fire immediately and thus go to top of queue. I believe the behavior you are seeing is expected and should be consistent cross platform and across different jdks

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.

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.

What is the best approach to schedule Callables which may time out in a polling situation?

I have several Callables which query for some JMX Beans, so each one may time out. I want to poll for values lets say every second. The most naive approach would be to start each in a separate thread, but I want to minimize the number of threads. Which options do I have to do it in a better way?
My interpretation is that you have a bunch of Callable objects which need to be polled at some interval. The trouble if you use a thread pool is that the pool will become contaminated with the slowest members, and your faster ones will be starved.
It sounds like you have control over the scheduling, so you might consider an exponential backoff approach. That is, after Callable X has run (and perhaps timed out), you wait 2 seconds instead of 1 second before rescheduling it. If it still fails, go to 4s, then 8s, etc. If you use a ScheduledThreadPoolExecutor, it comes with a built-in way to do this, allowing you to schedule your executions after a set delay.
If you set a constant timeout, this strategy will reduce your pool's susceptibility to monopolization by the slow ones. It is very difficult to get rid of this problem completely. Using a separate thread per queried object is really the only way to make sure you don't get starvation, and that can be very resource-intensive, as you say.
Another strategy is to bucket your pool into a fast one and a slow one. If an object is timing out (say more than N times), you move it to the slow pool. This keeps your fast pool fast, and while the slow ones all get in each others' way, at least they don't clog up the fast pool. If they have good statistics for a while, you can promote them to the fast pool again.
As soon as you submit a Callable you receive a Future - a handle to the future result. You can decide to wait for its completion for a given amount of time:
Future<String> future = executorService.submit(callable);
try {
future.get(1, TimeUnit.SECONDS);
} catch ( TimeoutException e ) {
future.cancel(true);
} catch ...
Calling get with a timeout allows you to receive an exception if the task has not been completed. This does not distinguish between not started tasks and started but not completed. On the other hand cancel will take a boolean parameter mayStopIfRunning so you can choose to e.g. only cancel tasks not yet scheduled.
i agree with robbotic...implementing a 'cachedThreadPool' will solve your problem as it will restrict the number of threads to the optimum level at the same time has timeouts which will free your un-utilized resources

Categories

Resources