forked from alibaba/transmittable-thread-local
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TransmittableThreadLocal.java
884 lines (806 loc) · 41 KB
/
TransmittableThreadLocal.java
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
package com.alibaba.ttl;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.Callable;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* {@link TransmittableThreadLocal}({@code TTL}) can transmit the value from the thread of submitting task to the thread of executing task.
* <p>
* <b>Note</b>:<br>
* {@link TransmittableThreadLocal} extends {@link InheritableThreadLocal},
* so {@link TransmittableThreadLocal} first is a {@link InheritableThreadLocal}.<br>
* If the <b>inheritable</b> ability from {@link InheritableThreadLocal} has <b>potential leaking problem</b>,
* you can disable the <b>inheritable</b> ability:
* <p>
* ❶ For thread pooling components({@link java.util.concurrent.ThreadPoolExecutor},
* {@link java.util.concurrent.ForkJoinPool}), Inheritable feature <b>should never</b> happen,
* since threads in thread pooling components is pre-created and pooled, these threads is <b>neutral</b> to biz logic/data.
* <br>
* Disable inheritable for thread pooling components by wrapping thread factories using methods
* {@link com.alibaba.ttl.threadpool.TtlExecutors#getDisableInheritableThreadFactory(java.util.concurrent.ThreadFactory) getDisableInheritableThreadFactory} /
* {@link com.alibaba.ttl.threadpool.TtlForkJoinPoolHelper#getDefaultDisableInheritableForkJoinWorkerThreadFactory() getDefaultDisableInheritableForkJoinWorkerThreadFactory}.
* <br>
* Or you can turn on "disable inheritable for thread pool" by {@link com.alibaba.ttl.threadpool.agent.TtlAgent}
* so as to wrap thread factories for thread pooling components automatically and transparently.
* <p>
* ❷ In other cases, disable inheritable by overriding method {@link #childValue(Object)}.
* <br>
* Whether the value should be inheritable or not can be controlled by the data owner,
* disable it <b>carefully</b> when data owner have a clear idea.
* <pre>{@code
* TransmittableThreadLocal<String> transmittableThreadLocal = new TransmittableThreadLocal<>() {
* protected String childValue(String parentValue) {
* return initialValue();
* }
* }}</pre>
* <p>
* More discussion about "disable the <b>inheritable</b> ability"
* see <a href="https://github.com/alibaba/transmittable-thread-local/issues/100">
* issue #100: disable Inheritable when it's not necessary and buggy</a>.
*
* @author Jerry Lee (oldratlee at gmail dot com)
* @author Yang Fang (snoop dot fy at gmail dot com)
* @see <a href="https://github.com/alibaba/transmittable-thread-local">user guide docs and code repo of TransmittableThreadLocal(TTL)</a>
* @see TtlRunnable
* @see TtlCallable
* @see com.alibaba.ttl.threadpool.TtlExecutors
* @see com.alibaba.ttl.threadpool.TtlExecutors#getTtlExecutor(java.util.concurrent.Executor)
* @see com.alibaba.ttl.threadpool.TtlExecutors#getTtlExecutorService(java.util.concurrent.ExecutorService)
* @see com.alibaba.ttl.threadpool.TtlExecutors#getTtlScheduledExecutorService(java.util.concurrent.ScheduledExecutorService)
* @see com.alibaba.ttl.threadpool.TtlExecutors#getDefaultDisableInheritableThreadFactory()
* @see com.alibaba.ttl.threadpool.TtlExecutors#getDisableInheritableThreadFactory(java.util.concurrent.ThreadFactory)
* @see com.alibaba.ttl.threadpool.TtlForkJoinPoolHelper
* @see com.alibaba.ttl.threadpool.TtlForkJoinPoolHelper#getDefaultDisableInheritableForkJoinWorkerThreadFactory()
* @see com.alibaba.ttl.threadpool.TtlForkJoinPoolHelper#getDisableInheritableForkJoinWorkerThreadFactory(java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory)
* @see com.alibaba.ttl.threadpool.agent.TtlAgent
* @since 0.10.0
*/
public class TransmittableThreadLocal<T> extends InheritableThreadLocal<T> implements TtlCopier<T> {
private static final Logger logger = Logger.getLogger(TransmittableThreadLocal.class.getName());
private final boolean disableIgnoreNullValueSemantics;
/**
* Default constructor. Create a {@link TransmittableThreadLocal} instance with "Ignore-Null-Value Semantics".
* <p>
* About "Ignore-Null-Value Semantics":
* <p>
* <ol>
* <li>If value is {@code null}(check by {@link #get()} method), do NOT transmit this {@code ThreadLocal}.</li>
* <li>If set {@code null} value, also remove value(invoke {@link #remove()} method).</li>
* </ol>
* <p>
* This is a pragmatic design decision:
* <ol>
* <li>use explicit value type rather than {@code null} value to express biz intent.</li>
* <li>safer and more robust code(avoid {@code NPE} risk).</li>
* </ol>
* <p>
* So it's strongly not recommended to use {@code null} value.
* <p>
* But the behavior of "Ignore-Null-Value Semantics" is NOT compatible with
* {@link ThreadLocal} and {@link InheritableThreadLocal},
* you can disable this behavior/semantics via using constructor {@link #TransmittableThreadLocal(boolean)}
* and setting parameter {@code disableIgnoreNullValueSemantics} to {@code true}.
* <p>
* More discussion about "Ignore-Null-Value Semantics" see
* <a href="https://github.com/alibaba/transmittable-thread-local/issues/157">Issue #157</a>.
*
* @see #TransmittableThreadLocal(boolean)
*/
public TransmittableThreadLocal() {
this(false);
}
/**
* Constructor, create a {@link TransmittableThreadLocal} instance
* with parameter {@code disableIgnoreNullValueSemantics} to control "Ignore-Null-Value Semantics".
*
* @param disableIgnoreNullValueSemantics disable "Ignore-Null-Value Semantics"
* @see #TransmittableThreadLocal()
* @since 2.11.3
*/
public TransmittableThreadLocal(boolean disableIgnoreNullValueSemantics) {
this.disableIgnoreNullValueSemantics = disableIgnoreNullValueSemantics;
}
/**
* Creates a transmittable thread local variable.
* The initial value({@link #initialValue()}) of the variable is
* determined by invoking the {@link #get()} method on the {@code Supplier}.
*
* @param <S> the type of the thread local's value
* @param supplier the supplier to be used to determine the initial value
* @return a new transmittable thread local variable
* @throws NullPointerException if the specified supplier is null
* @see #withInitialAndCopier(Supplier, TtlCopier)
* @since 2.12.2
*/
@NonNull
@SuppressWarnings("ConstantConditions")
public static <S> TransmittableThreadLocal<S> withInitial(@NonNull Supplier<? extends S> supplier) {
if (supplier == null) throw new NullPointerException("supplier is null");
return new SuppliedTransmittableThreadLocal<S>(supplier, null, null);
}
/**
* Creates a transmittable thread local variable.
* The initial value({@link #initialValue()}) of the variable is
* determined by invoking the {@link #get()} method on the {@code Supplier};
* and the child value({@link #childValue(Object)}) and the transmitting value({@link #copy(Object)}) of the variable is
* determined by invoking the {@link TtlCopier#copy(Object)} method on the {@code TtlCopier}.
*
* @param <S> the type of the thread local's value
* @param supplier the supplier to be used to determine the initial value
* @param copierForChildValueAndCopy the ttl copier to be used to determine the child value and the transmitting value
* @return a new transmittable thread local variable
* @throws NullPointerException if the specified supplier or copier is null
* @see #withInitial(Supplier)
* @since 2.12.3
*/
@NonNull
@ParametersAreNonnullByDefault
@SuppressWarnings("ConstantConditions")
public static <S> TransmittableThreadLocal<S> withInitialAndCopier(Supplier<? extends S> supplier, TtlCopier<S> copierForChildValueAndCopy) {
if (supplier == null) throw new NullPointerException("supplier is null");
if (copierForChildValueAndCopy == null) throw new NullPointerException("ttl copier is null");
return new SuppliedTransmittableThreadLocal<S>(supplier, copierForChildValueAndCopy, copierForChildValueAndCopy);
}
/**
* Creates a transmittable thread local variable.
* The initial value({@link #initialValue()}) of the variable is
* determined by invoking the {@link #get()} method on the {@code Supplier};
* and the child value({@link #childValue(Object)}) and the transmitting value({@link #copy(Object)}) of the variable is
* determined by invoking the {@link TtlCopier#copy(Object)} method on the {@code TtlCopier}.
* <p>
* <B><I>NOTE:</I></B><br>
* Recommend use {@link #withInitialAndCopier(Supplier, TtlCopier)} instead of this method.
* In most cases, the logic of determining the child value({@link #childValue(Object)})
* and the transmitting value({@link #copy(Object)}) should be the same.
*
* @param <S> the type of the thread local's value
* @param supplier the supplier to be used to determine the initial value
* @param copierForChildValue the ttl copier to be used to determine the child value
* @param copierForCopy the ttl copier to be used to determine the transmitting value
* @return a new transmittable thread local variable
* @throws NullPointerException if the specified supplier or copier is null
* @see #withInitial(Supplier)
* @see #withInitialAndCopier(Supplier, TtlCopier)
* @since 2.12.3
*/
@NonNull
@ParametersAreNonnullByDefault
@SuppressWarnings("ConstantConditions")
public static <S> TransmittableThreadLocal<S> withInitialAndCopier(Supplier<? extends S> supplier, TtlCopier<S> copierForChildValue, TtlCopier<S> copierForCopy) {
if (supplier == null) throw new NullPointerException("supplier is null");
if (copierForChildValue == null) throw new NullPointerException("ttl copier for child value is null");
if (copierForCopy == null) throw new NullPointerException("ttl copier for copy value is null");
return new SuppliedTransmittableThreadLocal<S>(supplier, copierForChildValue, copierForCopy);
}
/**
* An extension of ThreadLocal that obtains its initial value from the specified {@code Supplier}
* and obtains its child value and transmitting value from the specified ttl copier.
*/
private static final class SuppliedTransmittableThreadLocal<T> extends TransmittableThreadLocal<T> {
private final Supplier<? extends T> supplier;
private final TtlCopier<T> copierForChildValue;
private final TtlCopier<T> copierForCopy;
SuppliedTransmittableThreadLocal(Supplier<? extends T> supplier, TtlCopier<T> copierForChildValue, TtlCopier<T> copierForCopy) {
if (supplier == null) throw new NullPointerException("supplier is null");
this.supplier = supplier;
this.copierForChildValue = copierForChildValue;
this.copierForCopy = copierForCopy;
}
@Override
protected T initialValue() {
return supplier.get();
}
@Override
protected T childValue(T parentValue) {
if (copierForChildValue != null) return copierForChildValue.copy(parentValue);
else return super.childValue(parentValue);
}
@Override
public T copy(T parentValue) {
if (copierForCopy != null) return copierForCopy.copy(parentValue);
else return super.copy(parentValue);
}
}
/**
* Computes the value for this transmittable thread-local variable
* as a function of the source thread's value at the time the task
* Object is created.
* <p>
* This method is called from {@link TtlRunnable} or
* {@link TtlCallable} when it create, before the task is started.
* <p>
* This method merely returns reference of its source thread value(the shadow copy),
* and should be overridden if a different behavior is desired.
*
* @since 1.0.0
*/
public T copy(T parentValue) {
return parentValue;
}
/**
* Callback method before task object({@link TtlRunnable}/{@link TtlCallable}) execute.
* <p>
* Default behavior is to do nothing, and should be overridden
* if a different behavior is desired.
* <p>
* Do not throw any exception, just ignored.
*
* @since 1.2.0
*/
protected void beforeExecute() {
}
/**
* Callback method after task object({@link TtlRunnable}/{@link TtlCallable}) execute.
* <p>
* Default behavior is to do nothing, and should be overridden
* if a different behavior is desired.
* <p>
* Do not throw any exception, just ignored.
*
* @since 1.2.0
*/
protected void afterExecute() {
}
/**
* {@inheritDoc}
*/
@Override
public final T get() {
T value = super.get();
if (disableIgnoreNullValueSemantics || null != value) addThisToHolder();
return value;
}
/**
* {@inheritDoc}
*/
@Override
public final void set(T value) {
if (!disableIgnoreNullValueSemantics && null == value) {
// may set null to remove value
remove();
} else {
super.set(value);
addThisToHolder();
}
}
/**
* {@inheritDoc}
*/
@Override
public final void remove() {
removeThisFromHolder();
super.remove();
}
private void superRemove() {
super.remove();
}
private T copyValue() {
return copy(get());
}
// Note about the holder:
// 1. holder self is a InheritableThreadLocal(a *ThreadLocal*).
// 2. The type of value in the holder is WeakHashMap<TransmittableThreadLocal<Object>, ?>.
// 2.1 but the WeakHashMap is used as a *Set*:
// the value of WeakHashMap is *always* null, and never used.
// 2.2 WeakHashMap support *null* value.
private static final InheritableThreadLocal<WeakHashMap<TransmittableThreadLocal<Object>, ?>> holder =
new InheritableThreadLocal<WeakHashMap<TransmittableThreadLocal<Object>, ?>>() {
@Override
protected WeakHashMap<TransmittableThreadLocal<Object>, ?> initialValue() {
return new WeakHashMap<TransmittableThreadLocal<Object>, Object>();
}
@Override
protected WeakHashMap<TransmittableThreadLocal<Object>, ?> childValue(WeakHashMap<TransmittableThreadLocal<Object>, ?> parentValue) {
return new WeakHashMap<TransmittableThreadLocal<Object>, Object>(parentValue);
}
};
@SuppressWarnings("unchecked")
private void addThisToHolder() {
if (!holder.get().containsKey(this)) {
holder.get().put((TransmittableThreadLocal<Object>) this, null); // WeakHashMap supports null value.
}
}
private void removeThisFromHolder() {
holder.get().remove(this);
}
private static void doExecuteCallback(boolean isBefore) {
// copy TTL Instances to avoid `ConcurrentModificationException`
// even adjust TTL instances in biz lifecycle callbacks(beforeExecute/afterExecute)
WeakHashMap<TransmittableThreadLocal<Object>, ?> ttlInstances = new WeakHashMap<TransmittableThreadLocal<Object>, Object>(holder.get());
for (TransmittableThreadLocal<Object> threadLocal : ttlInstances.keySet()) {
try {
if (isBefore) threadLocal.beforeExecute();
else threadLocal.afterExecute();
} catch (Throwable t) {
if (logger.isLoggable(Level.WARNING)) {
logger.log(Level.WARNING, "TTL exception when " + (isBefore ? "beforeExecute" : "afterExecute") + ", cause: " + t, t);
}
}
}
}
/**
* Debug only method!
*/
static void dump(@Nullable String title) {
if (title != null && title.length() > 0) {
System.out.printf("Start TransmittableThreadLocal[%s] Dump...%n", title);
} else {
System.out.println("Start TransmittableThreadLocal Dump...");
}
for (TransmittableThreadLocal<Object> threadLocal : holder.get().keySet()) {
System.out.println(threadLocal.get());
}
System.out.println("TransmittableThreadLocal Dump end!");
}
/**
* Debug only method!
*/
static void dump() {
dump(null);
}
/**
* {@link Transmitter} transmit all values of {@link TransmittableThreadLocal}
* and registered {@link ThreadLocal}(registered by {@link Transmitter#registerThreadLocal})
* from the current thread to other thread by static methods
* {@link #capture()} => {@link #replay(Object)} => {@link #restore(Object)} (aka {@code CRR} operation).
* <p>
* {@link Transmitter} is <b><i>internal</i></b> manipulation api for <b><i>framework/middleware integration</i></b>;
* In general, you will <b><i>never</i></b> use it in the <i>biz/application code</i>!
*
* <h2>Framework/Middleware integration to TTL transmittance</h2>
* Below is the example code:
*
* <pre>{@code
* ///////////////////////////////////////////////////////////////////////////
* // in thread A, capture all TransmittableThreadLocal values of thread A
* ///////////////////////////////////////////////////////////////////////////
*
* Object captured = Transmitter.capture(); // (1)
*
* ///////////////////////////////////////////////////////////////////////////
* // in thread B
* ///////////////////////////////////////////////////////////////////////////
*
* // replay all TransmittableThreadLocal values from thread A
* Object backup = Transmitter.replay(captured); // (2)
* try {
* // your biz logic, run with the TransmittableThreadLocal values of thread B
* System.out.println("Hello");
* // ...
* return "World";
* } finally {
* // restore the TransmittableThreadLocal of thread B when replay
* Transmitter.restore(backup); // (3)
* }}</pre>
* <p>
* see the implementation code of {@link TtlRunnable} and {@link TtlCallable} for more actual code sample.
* <p>
* Of course, {@link #replay(Object)} and {@link #restore(Object)} operation can be simplified by util methods
* {@link #runCallableWithCaptured(Object, Callable)} or {@link #runSupplierWithCaptured(Object, Supplier)}
* and the adorable {@code Java 8 lambda syntax}.
* <p>
* Below is the example code:
*
* <pre>{@code
* ///////////////////////////////////////////////////////////////////////////
* // in thread A, capture all TransmittableThreadLocal values of thread A
* ///////////////////////////////////////////////////////////////////////////
*
* Object captured = Transmitter.capture(); // (1)
*
* ///////////////////////////////////////////////////////////////////////////
* // in thread B
* ///////////////////////////////////////////////////////////////////////////
*
* String result = runSupplierWithCaptured(captured, () -> {
* // your biz logic, run with the TransmittableThreadLocal values of thread A
* System.out.println("Hello");
* ...
* return "World";
* }); // (2) + (3)}</pre>
* <p>
* The reason of providing 2 util methods is the different {@code throws Exception} type
* to satisfy your biz logic({@code lambda}):
* <ol>
* <li>{@link #runCallableWithCaptured(Object, Callable)}: {@code throws Exception}</li>
* <li>{@link #runSupplierWithCaptured(Object, Supplier)}: No {@code throws}</li>
* </ol>
* <p>
* If you need the different {@code throws Exception} type,
* you can define your own util method(function interface({@code lambda}))
* with your own {@code throws Exception} type.
*
* <h2>ThreadLocal Integration</h2>
* If you can not rewrite the existed code which use {@link ThreadLocal} to {@link TransmittableThreadLocal},
* register the {@link ThreadLocal} instances via the methods
* {@link #registerThreadLocal(ThreadLocal, TtlCopier)}/{@link #registerThreadLocalWithShadowCopier(ThreadLocal)}
* to enhance the <b>Transmittable</b> ability for the existed {@link ThreadLocal} instances.
* <p>
* Below is the example code:
*
* <pre>{@code
* // the value of this ThreadLocal instance will be transmitted after registered
* Transmitter.registerThreadLocal(aThreadLocal, copyLambda);
*
* // Then the value of this ThreadLocal instance will not be transmitted after unregistered
* Transmitter.unregisterThreadLocal(aThreadLocal);}</pre>
*
* <B><I>Caution:</I></B><br>
* If the registered {@link ThreadLocal} instance is not {@link InheritableThreadLocal},
* the instance can NOT <B><I>{@code inherit}</I></B> value from parent thread(aka. the <b>inheritable</b> ability)!
*
* @author Yang Fang (snoop dot fy at gmail dot com)
* @author Jerry Lee (oldratlee at gmail dot com)
* @see TtlRunnable
* @see TtlCallable
* @since 2.3.0
*/
public static class Transmitter {
/**
* Capture all {@link TransmittableThreadLocal} and registered {@link ThreadLocal} values in the current thread.
*
* @return the captured {@link TransmittableThreadLocal} values
* @since 2.3.0
*/
@NonNull
public static Object capture() {
return new Snapshot(captureTtlValues(), captureThreadLocalValues());
}
private static HashMap<TransmittableThreadLocal<Object>, Object> captureTtlValues() {
HashMap<TransmittableThreadLocal<Object>, Object> ttl2Value = new HashMap<TransmittableThreadLocal<Object>, Object>();
for (TransmittableThreadLocal<Object> threadLocal : holder.get().keySet()) {
ttl2Value.put(threadLocal, threadLocal.copyValue());
}
return ttl2Value;
}
private static HashMap<ThreadLocal<Object>, Object> captureThreadLocalValues() {
final HashMap<ThreadLocal<Object>, Object> threadLocal2Value = new HashMap<ThreadLocal<Object>, Object>();
for (Map.Entry<ThreadLocal<Object>, TtlCopier<Object>> entry : threadLocalHolder.entrySet()) {
final ThreadLocal<Object> threadLocal = entry.getKey();
final TtlCopier<Object> copier = entry.getValue();
threadLocal2Value.put(threadLocal, copier.copy(threadLocal.get()));
}
return threadLocal2Value;
}
/**
* Replay the captured {@link TransmittableThreadLocal} and registered {@link ThreadLocal} values from {@link #capture()},
* and return the backup {@link TransmittableThreadLocal} values in the current thread before replay.
*
* @param captured captured {@link TransmittableThreadLocal} values from other thread from {@link #capture()}
* @return the backup {@link TransmittableThreadLocal} values before replay
* @see #capture()
* @since 2.3.0
*/
@NonNull
public static Object replay(@NonNull Object captured) {
final Snapshot capturedSnapshot = (Snapshot) captured;
return new Snapshot(replayTtlValues(capturedSnapshot.ttl2Value), replayThreadLocalValues(capturedSnapshot.threadLocal2Value));
}
@NonNull
private static HashMap<TransmittableThreadLocal<Object>, Object> replayTtlValues(@NonNull HashMap<TransmittableThreadLocal<Object>, Object> captured) {
HashMap<TransmittableThreadLocal<Object>, Object> backup = new HashMap<TransmittableThreadLocal<Object>, Object>();
for (final Iterator<TransmittableThreadLocal<Object>> iterator = holder.get().keySet().iterator(); iterator.hasNext(); ) {
TransmittableThreadLocal<Object> threadLocal = iterator.next();
// backup
backup.put(threadLocal, threadLocal.get());
// clear the TTL values that is not in captured
// avoid the extra TTL values after replay when run task
if (!captured.containsKey(threadLocal)) {
iterator.remove();
threadLocal.superRemove();
}
}
// set TTL values to captured
setTtlValuesTo(captured);
// call beforeExecute callback
doExecuteCallback(true);
return backup;
}
private static HashMap<ThreadLocal<Object>, Object> replayThreadLocalValues(@NonNull HashMap<ThreadLocal<Object>, Object> captured) {
final HashMap<ThreadLocal<Object>, Object> backup = new HashMap<ThreadLocal<Object>, Object>();
for (Map.Entry<ThreadLocal<Object>, Object> entry : captured.entrySet()) {
final ThreadLocal<Object> threadLocal = entry.getKey();
backup.put(threadLocal, threadLocal.get());
final Object value = entry.getValue();
if (value == threadLocalClearMark) threadLocal.remove();
else threadLocal.set(value);
}
return backup;
}
/**
* Clear all {@link TransmittableThreadLocal} and registered {@link ThreadLocal} values in the current thread,
* and return the backup {@link TransmittableThreadLocal} values in the current thread before clear.
*
* @return the backup {@link TransmittableThreadLocal} values before clear
* @since 2.9.0
*/
@NonNull
public static Object clear() {
final HashMap<TransmittableThreadLocal<Object>, Object> ttl2Value = new HashMap<TransmittableThreadLocal<Object>, Object>();
final HashMap<ThreadLocal<Object>, Object> threadLocal2Value = new HashMap<ThreadLocal<Object>, Object>();
for (Map.Entry<ThreadLocal<Object>, TtlCopier<Object>> entry : threadLocalHolder.entrySet()) {
final ThreadLocal<Object> threadLocal = entry.getKey();
threadLocal2Value.put(threadLocal, threadLocalClearMark);
}
return replay(new Snapshot(ttl2Value, threadLocal2Value));
}
/**
* Restore the backup {@link TransmittableThreadLocal} and
* registered {@link ThreadLocal} values from {@link #replay(Object)}/{@link #clear()}.
*
* @param backup the backup {@link TransmittableThreadLocal} values from {@link #replay(Object)}/{@link #clear()}
* @see #replay(Object)
* @see #clear()
* @since 2.3.0
*/
public static void restore(@NonNull Object backup) {
final Snapshot backupSnapshot = (Snapshot) backup;
restoreTtlValues(backupSnapshot.ttl2Value);
restoreThreadLocalValues(backupSnapshot.threadLocal2Value);
}
private static void restoreTtlValues(@NonNull HashMap<TransmittableThreadLocal<Object>, Object> backup) {
// call afterExecute callback
doExecuteCallback(false);
for (final Iterator<TransmittableThreadLocal<Object>> iterator = holder.get().keySet().iterator(); iterator.hasNext(); ) {
TransmittableThreadLocal<Object> threadLocal = iterator.next();
// clear the TTL values that is not in backup
// avoid the extra TTL values after restore
if (!backup.containsKey(threadLocal)) {
iterator.remove();
threadLocal.superRemove();
}
}
// restore TTL values
setTtlValuesTo(backup);
}
private static void setTtlValuesTo(@NonNull HashMap<TransmittableThreadLocal<Object>, Object> ttlValues) {
for (Map.Entry<TransmittableThreadLocal<Object>, Object> entry : ttlValues.entrySet()) {
TransmittableThreadLocal<Object> threadLocal = entry.getKey();
threadLocal.set(entry.getValue());
}
}
private static void restoreThreadLocalValues(@NonNull HashMap<ThreadLocal<Object>, Object> backup) {
for (Map.Entry<ThreadLocal<Object>, Object> entry : backup.entrySet()) {
final ThreadLocal<Object> threadLocal = entry.getKey();
threadLocal.set(entry.getValue());
}
}
private static class Snapshot {
final HashMap<TransmittableThreadLocal<Object>, Object> ttl2Value;
final HashMap<ThreadLocal<Object>, Object> threadLocal2Value;
private Snapshot(HashMap<TransmittableThreadLocal<Object>, Object> ttl2Value, HashMap<ThreadLocal<Object>, Object> threadLocal2Value) {
this.ttl2Value = ttl2Value;
this.threadLocal2Value = threadLocal2Value;
}
}
/**
* Util method for simplifying {@link #replay(Object)} and {@link #restore(Object)} operation.
*
* @param captured captured {@link TransmittableThreadLocal} values from other thread from {@link #capture()}
* @param bizLogic biz logic
* @param <R> the return type of biz logic
* @return the return value of biz logic
* @see #capture()
* @see #replay(Object)
* @see #restore(Object)
* @since 2.3.1
*/
public static <R> R runSupplierWithCaptured(@NonNull Object captured, @NonNull Supplier<R> bizLogic) {
final Object backup = replay(captured);
try {
return bizLogic.get();
} finally {
restore(backup);
}
}
/**
* Util method for simplifying {@link #clear()} and {@link #restore(Object)} operation.
*
* @param bizLogic biz logic
* @param <R> the return type of biz logic
* @return the return value of biz logic
* @see #clear()
* @see #restore(Object)
* @since 2.9.0
*/
public static <R> R runSupplierWithClear(@NonNull Supplier<R> bizLogic) {
final Object backup = clear();
try {
return bizLogic.get();
} finally {
restore(backup);
}
}
/**
* Util method for simplifying {@link #replay(Object)} and {@link #restore(Object)} operation.
*
* @param captured captured {@link TransmittableThreadLocal} values from other thread from {@link #capture()}
* @param bizLogic biz logic
* @param <R> the return type of biz logic
* @return the return value of biz logic
* @throws Exception the exception threw by biz logic
* @see #capture()
* @see #replay(Object)
* @see #restore(Object)
* @since 2.3.1
*/
public static <R> R runCallableWithCaptured(@NonNull Object captured, @NonNull Callable<R> bizLogic) throws Exception {
final Object backup = replay(captured);
try {
return bizLogic.call();
} finally {
restore(backup);
}
}
/**
* Util method for simplifying {@link #clear()} and {@link #restore(Object)} operation.
*
* @param bizLogic biz logic
* @param <R> the return type of biz logic
* @return the return value of biz logic
* @throws Exception the exception threw by biz logic
* @see #clear()
* @see #restore(Object)
* @since 2.9.0
*/
public static <R> R runCallableWithClear(@NonNull Callable<R> bizLogic) throws Exception {
final Object backup = clear();
try {
return bizLogic.call();
} finally {
restore(backup);
}
}
private static volatile WeakHashMap<ThreadLocal<Object>, TtlCopier<Object>> threadLocalHolder = new WeakHashMap<ThreadLocal<Object>, TtlCopier<Object>>();
private static final Object threadLocalHolderUpdateLock = new Object();
private static final Object threadLocalClearMark = new Object();
/**
* Register the {@link ThreadLocal}(including subclass {@link InheritableThreadLocal}) instances
* to enhance the <b>Transmittable</b> ability for the existed {@link ThreadLocal} instances.
* <p>
* If the registered {@link ThreadLocal} instance is {@link TransmittableThreadLocal} just ignores and return {@code true}.
* since a {@link TransmittableThreadLocal} instance itself has the {@code Transmittable} ability,
* it is unnecessary to register a {@link TransmittableThreadLocal} instance.
*
* <B><I>Caution:</I></B><br>
* If the registered {@link ThreadLocal} instance is not {@link InheritableThreadLocal},
* the instance can NOT <B><I>{@code inherit}</I></B> value from parent thread(aka. the <b>inheritable</b> ability)!
*
* @param threadLocal the {@link ThreadLocal} instance that to enhance the <b>Transmittable</b> ability
* @param copier the {@link TtlCopier}
* @return {@code true} if register the {@link ThreadLocal} instance and set {@code copier}, otherwise {@code false}
* @see #registerThreadLocal(ThreadLocal, TtlCopier, boolean)
* @since 2.11.0
*/
public static <T> boolean registerThreadLocal(@NonNull ThreadLocal<T> threadLocal, @NonNull TtlCopier<T> copier) {
return registerThreadLocal(threadLocal, copier, false);
}
/**
* Register the {@link ThreadLocal}(including subclass {@link InheritableThreadLocal}) instances
* to enhance the <b>Transmittable</b> ability for the existed {@link ThreadLocal} instances.
* <p>
* Use the shadow copier(transmit the reference directly),
* and should use method {@link #registerThreadLocal(ThreadLocal, TtlCopier)} to pass a customized {@link TtlCopier} explicitly
* if a different behavior is desired.
* <p>
* If the registered {@link ThreadLocal} instance is {@link TransmittableThreadLocal} just ignores and return {@code true}.
* since a {@link TransmittableThreadLocal} instance itself has the {@code Transmittable} ability,
* it is unnecessary to register a {@link TransmittableThreadLocal} instance.
*
* <B><I>Caution:</I></B><br>
* If the registered {@link ThreadLocal} instance is not {@link InheritableThreadLocal},
* the instance can NOT <B><I>{@code inherit}</I></B> value from parent thread(aka. the <b>inheritable</b> ability)!
*
* @param threadLocal the {@link ThreadLocal} instance that to enhance the <b>Transmittable</b> ability
* @return {@code true} if register the {@link ThreadLocal} instance and set {@code copier}, otherwise {@code false}
* @see #registerThreadLocal(ThreadLocal, TtlCopier)
* @see #registerThreadLocal(ThreadLocal, TtlCopier, boolean)
* @since 2.11.0
*/
@SuppressWarnings("unchecked")
public static <T> boolean registerThreadLocalWithShadowCopier(@NonNull ThreadLocal<T> threadLocal) {
return registerThreadLocal(threadLocal, (TtlCopier<T>) shadowCopier, false);
}
/**
* Register the {@link ThreadLocal}(including subclass {@link InheritableThreadLocal}) instances
* to enhance the <b>Transmittable</b> ability for the existed {@link ThreadLocal} instances.
* <p>
* If the registered {@link ThreadLocal} instance is {@link TransmittableThreadLocal} just ignores and return {@code true}.
* since a {@link TransmittableThreadLocal} instance itself has the {@code Transmittable} ability,
* it is unnecessary to register a {@link TransmittableThreadLocal} instance.
*
* <B><I>Caution:</I></B><br>
* If the registered {@link ThreadLocal} instance is not {@link InheritableThreadLocal},
* the instance can NOT <B><I>{@code inherit}</I></B> value from parent thread(aka. the <b>inheritable</b> ability)!
*
* @param threadLocal the {@link ThreadLocal} instance that to enhance the <b>Transmittable</b> ability
* @param copier the {@link TtlCopier}
* @param force if {@code true}, update {@code copier} to {@link ThreadLocal} instance
* when a {@link ThreadLocal} instance is already registered; otherwise, ignore.
* @return {@code true} if register the {@link ThreadLocal} instance and set {@code copier}, otherwise {@code false}
* @see #registerThreadLocal(ThreadLocal, TtlCopier)
* @since 2.11.0
*/
@SuppressWarnings("unchecked")
public static <T> boolean registerThreadLocal(@NonNull ThreadLocal<T> threadLocal, @NonNull TtlCopier<T> copier, boolean force) {
if (threadLocal instanceof TransmittableThreadLocal) {
logger.warning("register a TransmittableThreadLocal instance, this is unnecessary!");
return true;
}
synchronized (threadLocalHolderUpdateLock) {
if (!force && threadLocalHolder.containsKey(threadLocal)) return false;
WeakHashMap<ThreadLocal<Object>, TtlCopier<Object>> newHolder = new WeakHashMap<ThreadLocal<Object>, TtlCopier<Object>>(threadLocalHolder);
newHolder.put((ThreadLocal<Object>) threadLocal, (TtlCopier<Object>) copier);
threadLocalHolder = newHolder;
return true;
}
}
/**
* Register the {@link ThreadLocal}(including subclass {@link InheritableThreadLocal}) instances
* to enhance the <b>Transmittable</b> ability for the existed {@link ThreadLocal} instances.
* <p>
* Use the shadow copier(transmit the reference directly),
* and should use method {@link #registerThreadLocal(ThreadLocal, TtlCopier, boolean)} to pass a customized {@link TtlCopier} explicitly
* if a different behavior is desired.
* <p>
* If the registered {@link ThreadLocal} instance is {@link TransmittableThreadLocal} just ignores and return {@code true}.
* since a {@link TransmittableThreadLocal} instance itself has the {@code Transmittable} ability,
* it is unnecessary to register a {@link TransmittableThreadLocal} instance.
*
* <B><I>Caution:</I></B><br>
* If the registered {@link ThreadLocal} instance is not {@link InheritableThreadLocal},
* the instance can NOT <B><I>{@code inherit}</I></B> value from parent thread(aka. the <b>inheritable</b> ability)!
*
* @param threadLocal the {@link ThreadLocal} instance that to enhance the <b>Transmittable</b> ability
* @param force if {@code true}, update {@code copier} to {@link ThreadLocal} instance
* when a {@link ThreadLocal} instance is already registered; otherwise, ignore.
* @return {@code true} if register the {@link ThreadLocal} instance and set {@code copier}, otherwise {@code false}
* @see #registerThreadLocal(ThreadLocal, TtlCopier)
* @see #registerThreadLocal(ThreadLocal, TtlCopier, boolean)
* @since 2.11.0
*/
@SuppressWarnings("unchecked")
public static <T> boolean registerThreadLocalWithShadowCopier(@NonNull ThreadLocal<T> threadLocal, boolean force) {
return registerThreadLocal(threadLocal, (TtlCopier<T>) shadowCopier, force);
}
/**
* Unregister the {@link ThreadLocal} instances
* to remove the <b>Transmittable</b> ability for the {@link ThreadLocal} instances.
* <p>
* If the {@link ThreadLocal} instance is {@link TransmittableThreadLocal} just ignores and return {@code true}.
*
* @see #registerThreadLocal(ThreadLocal, TtlCopier)
* @see #registerThreadLocalWithShadowCopier(ThreadLocal)
* @since 2.11.0
*/
public static <T> boolean unregisterThreadLocal(@NonNull ThreadLocal<T> threadLocal) {
if (threadLocal instanceof TransmittableThreadLocal) {
logger.warning("unregister a TransmittableThreadLocal instance, this is unnecessary!");
return true;
}
synchronized (threadLocalHolderUpdateLock) {
if (!threadLocalHolder.containsKey(threadLocal)) return false;
WeakHashMap<ThreadLocal<Object>, TtlCopier<Object>> newHolder = new WeakHashMap<ThreadLocal<Object>, TtlCopier<Object>>(threadLocalHolder);
newHolder.remove(threadLocal);
threadLocalHolder = newHolder;
return true;
}
}
private static final TtlCopier<Object> shadowCopier = new TtlCopier<Object>() {
@Override
public Object copy(Object parentValue) {
return parentValue;
}
};
private Transmitter() {
throw new InstantiationError("Must not instantiate this class");
}
}
}