How can I disable an async thread in a web application and guarantee only 1 fire thread?
I want to cache an object in memory. Regenerating an object when the cache expires is pretty expensive, so I want to do the following:
When the cache "expires" I want to disable the asynchronous thread that will go over and rebuild the object, then reset the cache.
One thing I'm worried about is multithreaded firing to fetch an object into the cache, I want only one thread to do this, realizing that many people will end up on the site.
This may not be the best option for this, but I want to know how to do it.
a source to share
Are you looking for java.util.concurrent.Executors.newSingleThreadScheduledExecutor ():
Creates a single-threaded executor that can schedule the execution of commands after a specified delay, or execute them periodically. (Note that if this single thread terminates due to a runtime failure prior to shutdown, the new one will be busy if required to perform subsequent tasks.) Tasks are guaranteed to run sequentially and no more than one task is active at any given time. Unlike the equivalent newScheduledThreadPool (1), the returned executor is guaranteed not to be reconfigured to use additional threads.
a source to share
You have to use ScheduledExecutorService. If I wrote this, I would do it the same way:
Object cachedObject = null;
ReadWriteLock lock = new ReentrantReadWriteLock();
ScheduledExecutorService cacheService = Executors.newScheduledThreadPool(1);
cacheService.scheduleAtFixedRate(new Runnable(){
public void run(){
lock.writeLock().lock();
try{
cachedObjcet = //built object
}finally{
lock.writeLock().unlock();
}
}
}, 0, N, X);
//where
// N is the amount of time until expiriation
// X is the time units that N is represented by
public Object getCachedObject(){
lock.readLock().lock();
try{
return cachedObject;
}finally{
lock.readLock().unlock();
}
}
a source to share
you can use lock(this){}
in a section of code to ensure that only one thread can access it at a time.
alternatively you can cache a boolean and set it to true when you start your asynchronous thread by checking it before starting the specified thread and if it is false abort the scheduled operation
a source to share