3 * Copyright (C) 2015 EDIT
4 * European Distributed Institute of Taxonomy
5 * http://www.e-taxonomy.eu
7 * The contents of this file are subject to the Mozilla Public License Version 1.1
8 * See LICENSE.TXT at the top of this package for the full license terms.
10 package eu
.etaxonomy
.cdm
.api
.service
;
12 import java
.util
.ArrayList
;
13 import java
.util
.HashMap
;
14 import java
.util
.List
;
16 import java
.util
.UUID
;
17 import java
.util
.concurrent
.ConcurrentHashMap
;
19 import org
.springframework
.stereotype
.Component
;
21 import eu
.etaxonomy
.cdm
.common
.monitor
.IRestServiceProgressMonitor
;
24 * Manages monitors for long running jobs.
31 public class ProgressMonitorManager
<T
extends IRestServiceProgressMonitor
> {
33 private final Map
<UUID
, T
> monitors
= new ConcurrentHashMap
<UUID
, T
>();
35 private final Map
<UUID
, Long
> timeoutMap
= new HashMap
<UUID
, Long
>();
37 private Thread cleanUpThread
= null;
40 * Time out in minutes for monitors which are done.
41 * A monitor which is set done will be removed after this interval.
43 private final int cleanUpTimeout
= 1;
48 private final int cleanUpInterval
= 1000 * 10; // 10 seconds
50 public ProgressMonitorManager() {
52 this.cleanUpThread
= new Thread(){
59 sleep(cleanUpInterval
);
60 } catch (InterruptedException e
) {
67 cleanUpThread
.start();
71 * run every n minutes clean up monitors which have been marked done x minutes ago
73 private void scheduledCleanUp() {
75 List
<UUID
> timedOutMonitors
= new ArrayList
<UUID
>();
76 IRestServiceProgressMonitor monitor
;
78 long now
= System
.currentTimeMillis();
79 long nextTimeout
= now
+ cleanUpTimeout
* 1000 * 60;
82 // add monitors which are stopped or done to the timeoutMap
83 for(UUID uuid
: monitors
.keySet()){
84 monitor
= monitors
.get(uuid
);
85 if((monitor
.isFailed() || monitor
.isDone())){
86 if(!timeoutMap
.containsKey(uuid
)){
87 timeoutMap
.put(uuid
, nextTimeout
);
90 if(monitor
.hasFeedbackWaitTimedOut()) {
95 // check with monitor has timed out
96 for(UUID uuid
: timeoutMap
.keySet()){
97 if(timeoutMap
.get(uuid
) <= now
){
98 timedOutMonitors
.add(uuid
);
102 //finally remove the monitors
103 for(UUID uuid
: timedOutMonitors
){
104 timeoutMap
.remove(uuid
);
105 monitors
.remove(uuid
);
110 public UUID
registerMonitor(T monitor
){
111 UUID uuid
= UUID
.randomUUID();
112 monitors
.put(uuid
, monitor
);
116 public IRestServiceProgressMonitor
getMonitor(UUID uuid
) {
120 return monitors
.get(uuid
);
124 * returns true if the {@link IRestServiceProgressMonitor} identified by the <code>uuid</code>
125 * exists and if it is still indicating a running thread
129 public boolean isMonitorRunning(UUID uuid
) {
130 IRestServiceProgressMonitor monitor
= getMonitor(uuid
);
131 return monitor
!= null && !monitor
.isCanceled() && !monitor
.isDone() && !monitor
.isFailed();
134 public Map
<UUID
, T
> getMonitors() {