Project

General

Profile

1
package gr.uoa.di.driver.util;
2

    
3
import java.util.concurrent.ScheduledExecutorService;
4
import java.util.concurrent.TimeUnit;
5

    
6
import org.apache.log4j.Logger;
7

    
8
import eu.dnetlib.api.DriverService;
9

    
10
/**
11
 * An implementation of the service locator that keeps a cache of the service
12
 * and refreshes it periodically.
13
 * 
14
 * The actual task of service discovery is performed by a locator that is 
15
 * injected. 
16
 * 
17
 * @author <a href="mailto:antleb@di.uoa.gr">Antonis Lempesis</a>
18
 *
19
 * @param <S> the service type
20
 */
21
public class RefreshingServiceLocator<S extends DriverService> implements
22
		ServiceLocator<S> {
23
	/** The locator used to discover the service */
24
	private ServiceLocator<S> locator = null;
25
	/** the cached instance of the service */
26
	private S service = null;
27
	/** the executor that runs the refresh tasks */
28
	private ScheduledExecutorService executor = null;
29
	/** the discovery period in milliseconds*/
30
	private long period = 0;
31

    
32
	@Override
33
	public synchronized S getService() {
34
		if (service == null)
35
			init();
36
		
37
		return service;
38
	}
39

    
40
	/** 
41
	 * Called to initialize the locator. Performs the first service lookup and
42
	 * also schedules the periodic refresh of the cache. 
43
	 * 
44
	 * */
45
	private void init() {
46
		this.service = locator.getService();
47

    
48
		executor.scheduleWithFixedDelay(new RefreshTask(), period, period,
49
				TimeUnit.MILLISECONDS);
50
	}
51

    
52
	/**
53
	 * A very simple runnable that refreshed the cache. No synchronization is
54
	 * needed during cache refresh: The old instance will be returned while the
55
	 * locator is working to refresh the cache.
56
	 * 
57
	 * @author <a href="mailto:antleb@di.uoa.gr">Antonis Lempesis</a>
58
	 *
59
	 */
60
	private class RefreshTask implements Runnable {
61
		private Logger logger = Logger.getLogger(RefreshTask.class);
62

    
63
		@Override
64
		public void run() {
65
			try {
66
				logger.debug("Refreshing service cache");
67
				service = locator.getService();
68
			} catch (Exception e) {
69
				logger.info("Error refreshing service", e);
70
			}
71
		}
72
	}
73

    
74
	public ServiceLocator<S> getLocator() {
75
		return locator;
76
	}
77

    
78
	public void setLocator(ServiceLocator<S> locator) {
79
		this.locator = locator;
80
	}
81

    
82
	public ScheduledExecutorService getExecutor() {
83
		return executor;
84
	}
85

    
86
	public void setExecutor(ScheduledExecutorService executor) {
87
		this.executor = executor;
88
	}
89

    
90
	public long getPeriod() {
91
		return period;
92
	}
93

    
94
	public void setPeriod(long period) {
95
		this.period = period;
96
	}
97
}
(2-2/6)