2 * Copyright (C) 2015 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
9 package eu
.etaxonomy
.cdm
.api
.service
;
11 import java
.util
.ArrayList
;
12 import java
.util
.HashMap
;
13 import java
.util
.List
;
15 import java
.util
.UUID
;
16 import java
.util
.concurrent
.ConcurrentHashMap
;
18 import org
.springframework
.stereotype
.Component
;
20 import eu
.etaxonomy
.cdm
.common
.monitor
.IRestServiceProgressMonitor
;
23 * Manages monitors for long running jobs.
30 public class ProgressMonitorManager
<T
extends IRestServiceProgressMonitor
> {
32 private final Map
<UUID
, T
> monitors
= new ConcurrentHashMap
<UUID
, T
>();
34 private final Map
<UUID
, Long
> timeoutMap
= new HashMap
<UUID
, Long
>();
36 private Thread cleanUpThread
= null;
39 * Time out in minutes for monitors which are done.
40 * A monitor which is set done will be removed after this interval.
42 private final int cleanUpTimeout
= 1;
47 private final int cleanUpInterval
= 1000 * 10; // 10 seconds
49 public ProgressMonitorManager() {
51 this.cleanUpThread
= new Thread(){
58 sleep(cleanUpInterval
);
59 } catch (InterruptedException e
) {
66 cleanUpThread
.start();
70 * run every n minutes clean up monitors which have been marked done x minutes ago
72 private void scheduledCleanUp() {
74 List
<UUID
> timedOutMonitors
= new ArrayList
<UUID
>();
75 IRestServiceProgressMonitor monitor
;
77 long now
= System
.currentTimeMillis();
78 long nextTimeout
= now
+ cleanUpTimeout
* 1000 * 60;
81 // add monitors which are stopped or done to the timeoutMap
82 for(UUID uuid
: monitors
.keySet()){
83 monitor
= monitors
.get(uuid
);
84 if((monitor
.isFailed() || monitor
.isDone())){
85 if(!timeoutMap
.containsKey(uuid
)){
86 timeoutMap
.put(uuid
, nextTimeout
);
89 if(monitor
.hasFeedbackWaitTimedOut()) {
94 // check with monitor has timed out
95 for(UUID uuid
: timeoutMap
.keySet()){
96 if(timeoutMap
.get(uuid
) <= now
){
97 timedOutMonitors
.add(uuid
);
101 //finally remove the monitors
102 for(UUID uuid
: timedOutMonitors
){
103 timeoutMap
.remove(uuid
);
104 monitors
.remove(uuid
);
109 public UUID
registerMonitor(T monitor
){
110 UUID uuid
= UUID
.randomUUID();
111 monitors
.put(uuid
, monitor
);
115 public IRestServiceProgressMonitor
getMonitor(UUID uuid
) {
119 return monitors
.get(uuid
);
123 * returns true if the {@link IRestServiceProgressMonitor} identified by the <code>uuid</code>
124 * exists and if it is still indicating a running thread
128 public boolean isMonitorRunning(UUID uuid
) {
129 IRestServiceProgressMonitor monitor
= getMonitor(uuid
);
130 return monitor
!= null && !monitor
.isCanceled() && !monitor
.isDone() && !monitor
.isFailed();
133 public Map
<UUID
, T
> getMonitors() {