1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase;
20
21 import org.apache.commons.logging.Log;
22 import org.apache.commons.logging.LogFactory;
23
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.Map;
27 import java.util.ServiceLoader;
28
29
30
31
32
33 public class CompatibilitySingletonFactory extends CompatibilityFactory {
34 private static final Log LOG = LogFactory.getLog(CompatibilitySingletonFactory.class);
35 private static final Map<Class, Object> instances = new HashMap<Class, Object>();
36
37
38
39
40 protected CompatibilitySingletonFactory() { }
41
42
43
44
45
46
47 @SuppressWarnings("unchecked")
48 public static synchronized <T> T getInstance(Class<T> klass) {
49 T instance = (T) instances.get(klass);
50 if (instance == null) {
51 try {
52 ServiceLoader<T> loader = ServiceLoader.load(klass);
53 Iterator<T> it = loader.iterator();
54 instance = it.next();
55 if (it.hasNext()) {
56 StringBuilder msg = new StringBuilder();
57 msg.append("ServiceLoader provided more than one implementation for class: ")
58 .append(klass)
59 .append(", using implementation: ").append(instance.getClass())
60 .append(", other implementations: {");
61 while (it.hasNext()) {
62 msg.append(it.next()).append(" ");
63 }
64 msg.append("}");
65 LOG.warn(msg);
66 }
67 } catch (Exception e) {
68 throw new RuntimeException(createExceptionString(klass), e);
69 } catch (Error e) {
70 throw new RuntimeException(createExceptionString(klass), e);
71 }
72
73
74 if (instance == null) {
75 throw new RuntimeException(createExceptionString(klass));
76 }
77 instances.put(klass, instance);
78 }
79 return instance;
80 }
81 }