1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
|
/*
* Copyright 2000-2018 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.util;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinResponse;
import com.vaadin.server.VaadinService;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.UI;
/**
* Keeps track of various current instances for the current thread. All the
* instances are automatically cleared after handling a request from the client
* to avoid leaking memory.
* <p>
* Please note that the instances are stored using {@link WeakReference}. This
* means that the a current instance value may suddenly disappear if there a no
* other references to the object.
* <p>
* Currently the framework uses the following instances:
* </p>
* <p>
* {@link UI}, {@link VaadinService}, {@link VaadinSession},
* {@link VaadinRequest}, {@link VaadinResponse}.
* </p>
*
* @author Vaadin Ltd
* @since 7.0.0
*/
public class CurrentInstance implements Serializable {
private static final Object NULL_OBJECT = new Object();
private static final CurrentInstance CURRENT_INSTANCE_NULL = new CurrentInstance(
NULL_OBJECT);
private static final ConcurrentHashMap<Class<?>, CurrentInstanceFallbackResolver<?>> fallbackResolvers = new ConcurrentHashMap<Class<?>, CurrentInstanceFallbackResolver<?>>();
private final WeakReference<Object> instance;
private static final ThreadLocal<Map<Class<?>, CurrentInstance>> INSTANCES = new ThreadLocal<>();
private CurrentInstance(Object instance) {
this.instance = new WeakReference<>(instance);
}
/**
* Gets the current instance of a specific type if available.
* <p>
* When a current instance of the specific type is not found, the
* {@link CurrentInstanceFallbackResolver} registered via
* {@link #defineFallbackResolver(Class, CurrentInstanceFallbackResolver)}
* (if any) is invoked.
*
* @param type
* the class to get an instance of
* @return the current instance or the provided type, or <code>null</code>
* if there is no current instance.
*/
public static <T> T get(Class<T> type) {
T result = doGet(type);
if (result != null) {
return result;
}
CurrentInstanceFallbackResolver<?> fallbackResolver = fallbackResolvers
.get(type);
if (fallbackResolver != null) {
return (T) fallbackResolver.resolve();
}
return null;
}
private static <T> T doGet(Class<T> type) {
Map<Class<?>, CurrentInstance> map = INSTANCES.get();
if (map == null) {
return null;
}
CurrentInstance currentInstance = map.get(type);
if (currentInstance != null) {
Object value = currentInstance.instance.get();
if (value == null) {
/*
* This is believed to never actually happen since the
* ThreadLocal should only outlive the referenced object on
* threads that are not doing anything related to Vaadin, which
* should thus never invoke CurrentInstance.get().
*
* At this point, there might also be other values that have
* been collected, so we'll scan the entire map and remove stale
* CurrentInstance objects. Using a ReferenceQueue could make
* this assumingly rare case slightly more efficient, but would
* significantly increase the complexity of the code for
* maintaining a separate ReferenceQueue for each Thread.
*/
removeStaleInstances(map);
if (map.isEmpty()) {
INSTANCES.remove();
}
return null;
}
return type.cast(value);
} else {
return null;
}
}
/**
* Adds a CurrentInstanceFallbackResolver, that is triggered when
* {@link #get(Class)} can't find a suitable instance for the given type
* parameter.
*
* @param type
* the class used on {@link #get(Class)} invocations to retrieve
* the current instance
* @param fallbackResolver
* the resolver, not <code>null</code>
*
* @throws IllegalArgumentException
* if there's already a defined fallback resolver for the given
* type
* @since 8.5.2
*/
public static <T> void defineFallbackResolver(Class<T> type,
CurrentInstanceFallbackResolver<T> fallbackResolver) {
if (fallbackResolver == null) {
throw new IllegalArgumentException(
"The fallback resolver can not be null.");
}
if (fallbackResolvers.putIfAbsent(type, fallbackResolver) != null) {
throw new IllegalArgumentException(
"A fallback resolver for the type " + type
+ " is already defined.");
}
}
private static void removeStaleInstances(
Map<Class<?>, CurrentInstance> map) {
for (Iterator<Entry<Class<?>, CurrentInstance>> iterator = map
.entrySet().iterator(); iterator.hasNext();) {
Entry<Class<?>, CurrentInstance> entry = iterator.next();
Object instance = entry.getValue().instance.get();
if (instance == null) {
iterator.remove();
getLogger().log(Level.FINE,
"CurrentInstance for {0} has been garbage collected.",
entry.getKey());
}
}
}
/**
* Sets the current instance of the given type.
*
* @see ThreadLocal
*
* @param type
* the class that should be used when getting the current
* instance back
* @param instance
* the actual instance
*/
public static <T> CurrentInstance set(Class<T> type, T instance) {
Map<Class<?>, CurrentInstance> map = INSTANCES.get();
CurrentInstance previousInstance = null;
if (instance == null) {
// remove the instance
if (map != null) {
previousInstance = map.remove(type);
if (map.isEmpty()) {
INSTANCES.remove();
map = null;
}
}
} else {
assert type.isInstance(instance) : "Invald instance type";
if (map == null) {
map = new HashMap<>();
INSTANCES.set(map);
}
previousInstance = map.put(type, new CurrentInstance(instance));
}
if (previousInstance == null) {
previousInstance = CURRENT_INSTANCE_NULL;
}
return previousInstance;
}
/**
* Clears all current instances.
*/
public static void clearAll() {
INSTANCES.remove();
}
/**
* Restores the given instances to the given values. Note that this should
* only be used internally to restore Vaadin classes.
*
* @since 7.1
*
* @param old
* A Class -> CurrentInstance map to set as current instances
*/
public static void restoreInstances(Map<Class<?>, CurrentInstance> old) {
boolean removeStale = false;
for (Class c : old.keySet()) {
CurrentInstance ci = old.get(c);
Object v = ci.instance.get();
if (v == null) {
removeStale = true;
} else if (v == NULL_OBJECT) {
/*
* NULL_OBJECT is used to identify objects that are null when
* #setCurrent(UI) or #setCurrent(VaadinSession) are called on a
* CurrentInstance. Without this a reference to an already
* collected instance may be left in the CurrentInstance when it
* really should be restored to null.
*
* One example case that this fixes:
* VaadinService.runPendingAccessTasks() clears all current
* instances and then sets everything but the UI. This makes
* UI.accessSynchronously() save these values before calling
* setCurrent(UI), which stores UI=null in the map it returns.
* This map will be restored after UI.accessSync(), which,
* unless it respects null values, will just leave the wrong UI
* instance registered.
*/
v = null;
}
set(c, v);
}
if (removeStale) {
removeStaleInstances(old);
}
}
/**
* Gets the currently set instances so that they can later be restored using
* {@link #restoreInstances(Map)}.
*
* @since 8.0
*
* @return a map containing the current instances
*/
public static Map<Class<?>, CurrentInstance> getInstances() {
Map<Class<?>, CurrentInstance> map = INSTANCES.get();
if (map == null) {
return Collections.emptyMap();
} else {
Map<Class<?>, CurrentInstance> copy = new HashMap<>();
boolean removeStale = false;
for (Class<?> c : map.keySet()) {
CurrentInstance ci = map.get(c);
if (ci.instance.get() == null) {
removeStale = true;
} else {
copy.put(c, ci);
}
}
if (removeStale) {
removeStaleInstances(map);
if (map.isEmpty()) {
INSTANCES.remove();
}
}
return copy;
}
}
/**
* Sets current instances for the UI and all related classes. The previously
* defined values can be restored by passing the returned map to
* {@link #restoreInstances(Map)}.
*
* @since 7.1
*
* @param ui
* The UI
* @return A map containing the old values of the instances that this method
* updated.
*/
public static Map<Class<?>, CurrentInstance> setCurrent(UI ui) {
Map<Class<?>, CurrentInstance> old = setCurrent(ui.getSession());
old.put(UI.class, set(UI.class, ui));
return old;
}
/**
* Sets current instances for the {@link VaadinSession} and all related
* classes. The previously defined values can be restored by passing the
* returned map to {@link #restoreInstances(Map)}.
*
* @since 7.1
*
* @param session
* The VaadinSession
* @return A map containing the old values of the instances this method
* updated.
*/
public static Map<Class<?>, CurrentInstance> setCurrent(
VaadinSession session) {
Map<Class<?>, CurrentInstance> old = new HashMap<>();
old.put(VaadinSession.class, set(VaadinSession.class, session));
VaadinService service = null;
if (session != null) {
service = session.getService();
}
old.put(VaadinService.class, set(VaadinService.class, service));
return old;
}
private static Logger getLogger() {
return Logger.getLogger(CurrentInstance.class.getName());
}
}
|