Project

General

Profile

Download (2.35 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2015 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
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.
8
*/
9
package eu.etaxonomy.cdm.common.monitor;
10

    
11
import java.io.Serializable;
12
import java.util.concurrent.ConcurrentHashMap;
13

    
14
import org.apache.log4j.Logger;
15

    
16
/**
17
 * Thread class to be used to run monitored jobs
18
 *
19
 * @author cmathew
20
 * @since 22 Oct 2015
21
 *
22
 */
23
public abstract class RemotingProgressMonitorThread extends Thread {
24

    
25
    private static ConcurrentHashMap<IRemotingProgressMonitor, RemotingProgressMonitorThread> monitorsInProgress =
26
            new ConcurrentHashMap<IRemotingProgressMonitor, RemotingProgressMonitorThread>();
27

    
28
    private IRemotingProgressMonitor monitor;
29
    @SuppressWarnings("unused")
30
    private static final Logger logger = Logger.getLogger(RemotingProgressMonitorThread.class);
31

    
32
    public void setMonitor(IRemotingProgressMonitor monitor) {
33
        if(monitor == null) {
34
            throw new IllegalStateException("Monitor is null");
35
        }
36
        this.monitor = monitor;
37
    }
38

    
39
    /**
40
     * {@inheritDoc}
41
     */
42
    @Override
43
    public void run() {
44
        try {
45
            monitorsInProgress.put(monitor, this);
46
            monitor.setResult(doRun(monitor));
47
        } catch(Exception ex) {
48
            logger.info("Exception in RemotingProgressMonitorThread ", ex);
49
            monitor.setResult(ex);
50
            monitor.setIsFailed(true);
51
        }
52
        monitor.done();
53
        monitorsInProgress.remove(monitor);
54
    }
55

    
56
    /**
57
     * Executes the monitored job.
58
     *
59
     * @param monitor to be updated by the monitored job
60
     * @return result object
61
     */
62
    public abstract Serializable doRun(IRemotingProgressMonitor monitor);
63

    
64
    /**
65
     * Returns a currently running monitor thread corresponding to the
66
     * given monitor.
67
     *
68
     * @param monitor for which the thread
69
     * @return
70
     */
71
    protected static RemotingProgressMonitorThread getMonitorThread(IRemotingProgressMonitor monitor) {
72
        return monitorsInProgress.get(monitor);
73
    }
74

    
75
    /**
76
     * {@inheritDoc}
77
     */
78
    @Override
79
    public void interrupt() {
80
        super.interrupt();
81
        monitor.setCanceled(true);
82
        monitor.done();
83
        monitorsInProgress.remove(monitor);
84
    }
85

    
86
}
(8-8/10)