Reputation: 33
I have many facilities. Whenever facilities are turned on they call some class so that they can run at fixed Scheduled rate. If the facilities is closed i need to shutdown thread for that particular facility. How can i achieve that i am getting RejectedExecutionException when i try to shutdown and reopen the same facility later . Thanks for help. My code is similiar like as follows:
private static final ScheduledExecutorService svc = Executors
.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> syncThreadHandle = null;
public static void start(final String str1, final String str2) {
syncThreadHandle = svc.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("First string for this thread str1 " + str1
+ " Str2 " + str2);
}
}, 0, 1, TimeUnit.MINUTES);
}
public static void stop(final String str1, final String str2) {
svc.shutdown();
}
// and from another class i am using this.
public static void main(String args[])
{
ProcessFixedRun.start("hi", "hello");
ProcessFixedRun.start("hi agaIN", "hello again");
ProcessFixedRun.stop("hi", "hello");
}
How can i find the thread for that particular facility. I am not good at threads. Any help will be appreciated thanks
Upvotes: 3
Views: 1252
Reputation: 116918
Have you tried syncThreadHandle.cancel(true)
? You should use true
if you want it to interrupt the current running thread otherwise false
. I'm not sure if it will be rescheduled however.
If it does get rescheduled then you may have no choice but to put some sort of boolean that will disable the task. Something like:
@Override
public void run() {
if (!stillRunning) {
return false;
}
...
Upvotes: 1
Reputation: 40266
Can you store the ScheduleFuture in a map then cancel based on the key?
static ConcurrentMap<String,ScheduledFuture<?>> futures = new ConcurrentHashMap<>();
public static void start(final String str1, final String str2) {
String key = str1+str2;
futures.put(key , syncThreadHandle = svc.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("First string for this thread str1 " + str1
+ " Str2 " + str2);
}
}, 0, 1, TimeUnit.MINUTES));
}
public static void stop(final String str1, final String str2) {
futures.get(str1+str2).cancel(true);
}
The key can be either str1 or str2 (or both?).
Upvotes: 2