let's say I have lot of timers defined in the app.
@Startup
@Singleton
public class ScheduleManager {
@Resource
TimerService timerService;
Map<Long, Timer> timerMap;
@PostConstruct
void init() {
timerMap = new HashMap<>();
for (int i = 0; i < 10; i++) {
TimerConfig tc = new TimerConfig("someEntityId", true);
Timer timer = timerService.createSingleActionTimer(new Date(TimeUnit.DAYS.toMillis(i)), tc);
timerMap.put((long) i, timer);
}
}
public void cancelTimerById(long i) {
Timer timer = timerMap.get(i);
if(timer != null) {
timerMap.remove(i); //release the reference from Map
timer.cancel();
}
}
}
Is it safe/possible to cancel timers like that?
On other solution would be:
public void cancelTimerById(long i) {
for(Timer timer : timerService.getTimers()) {
if(Long.valueOf(timer.getInfo().toString()).equals(i)) {
timer.cancel();
}
}
}
But this is a bit too much iteration for each canceling...
My concern is keeping the instances of singleActionTimers (or other periodical timers) in a map. (for GC clean up).
Thanks
Aucun commentaire:
Enregistrer un commentaire