-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1496 lines (524 loc) · 86.1 KB
/
index.html
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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">
<link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">
<meta name="keywords" content="Hexo, NexT" />
<meta name="description" content="Internet|Software|Banking|Security, Java Latest Features, Spring Suite, Cryptography, Payments...">
<meta property="og:type" content="website">
<meta property="og:title" content="Xu Lei's Techblog">
<meta property="og:url" content="http://yoursite.com/index.html">
<meta property="og:site_name" content="Xu Lei's Techblog">
<meta property="og:description" content="Internet|Software|Banking|Security, Java Latest Features, Spring Suite, Cryptography, Payments...">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Xu Lei's Techblog">
<meta name="twitter:description" content="Internet|Software|Banking|Security, Java Latest Features, Spring Suite, Cryptography, Payments...">
<script type="text/javascript" id="hexo.configurations">
var NexT = window.NexT || {};
var CONFIG = {
root: '/',
scheme: 'Pisces',
version: '5.1.4',
sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
fancybox: true,
tabs: true,
motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
duoshuo: {
userId: '0',
author: '博主'
},
algolia: {
applicationID: '',
apiKey: '',
indexName: '',
hits: {"per_page":10},
labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
}
};
</script>
<link rel="canonical" href="http://yoursite.com/"/>
<title>Xu Lei's Techblog</title>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container sidebar-position-left
page-home">
<div class="headband"></div>
<a href="https://github.com/xljiadahao/Snippets.git"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/a6677b08c955af8400f44c6298f40e7d19cc5b2d/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f677261795f3664366436642e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png"></a>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-brand-wrapper">
<div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">Xu Lei's Techblog</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle">徐磊的技术博客</p>
</div>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
</div>
<nav class="site-nav">
<ul id="menu" class="menu">
<li class="menu-item menu-item-home">
<a href="/" rel="section">
<i class="menu-item-icon fa fa-fw fa-home"></i> <br />
首页
</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags/" rel="section">
<i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
标签
</a>
</li>
<li class="menu-item menu-item-categories">
<a href="/categories/" rel="section">
<i class="menu-item-icon fa fa-fw fa-th"></i> <br />
分类
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives/" rel="section">
<i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
归档
</a>
</li>
<li class="menu-item menu-item-commonweal">
<a href="/404/" rel="section">
<i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
公益404
</a>
</li>
<li class="menu-item menu-item-payment">
<a href="/payment" rel="section">
<i class="menu-item-icon fa fa-fw fa-paypal"></i> <br />
支付Payment
</a>
</li>
</ul>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<section id="posts" class="posts-expand">
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/01/20/Concurrency-高并发-Future-and-CompletableFuture/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="Xu Lei">
<meta itemprop="description" content="">
<meta itemprop="image" content="https://avatars2.githubusercontent.com/u/7018287">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="Xu Lei's Techblog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2020/01/20/Concurrency-高并发-Future-and-CompletableFuture/" itemprop="url">Concurrency 高并发 - Future and CompletableFuture</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2020-01-20T00:00:00+08:00">
2020-01-20
</time>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>Future class provides a very easy way to execute async operations. As of AIO, Future class manages a seperated thread to do the IO operation asynchronously. CompletableFuture is introduced by JDK 1.8 as the enhanced Future async model. It brings the complex future tasks pipeline with the functional interfaces which are also introduced by JDK 1.8. To understand this blog better, the pre-condition is the knowledge of the functional interfaces of JDK 1.8 <a href="https://xljiadahao.github.io/2018/02/04/Java-8-Features/" target="_blank" rel="noopener">Java 8 Features</a>.</p>
<p><em>Sample: <em>com.snippet.concurrent.future</em> of the Snippets repository in <a href="https://github.com/xljiadahao/Snippets.git" target="_blank" rel="noopener">GitHub</a>.</em></p>
<p><code>Future</code><br>Future is a interface which defines the basic operations to manage the asynchronous task, but Future itself cannot init a thread. Thus, let’s use FutureTask for the demo code. <code>FutureTask</code> implements RunnableFuture, while RunnableFuture is a interface which extends Runnable, Future, so FutureTask has all the Future async task features as well as the threading capability.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">public class AsyncCallableTask implements Callable<String> {</span><br><span class="line"> public String call() throws Exception { ... }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">AsyncCallableTask task = new AsyncCallableTask();</span><br><span class="line">FutureTask<String> futureTask = new FutureTask<>(task);</span><br><span class="line">new Thread(futureTask).start();</span><br><span class="line">boolean isDone = futureTask.isDone();</span><br><span class="line">while(!isDone) {</span><br><span class="line"> System.out.println("isDone: " + isDone + ", waiting 4 seconds for the downstream service call, do something else. "</span><br><span class="line"> + Thread.currentThread().getName());</span><br><span class="line"> Thread.sleep(4000);</span><br><span class="line"> isDone = futureTask.isDone();</span><br><span class="line"> Random r = new Random();</span><br><span class="line"> int randomTimeout = r.nextInt(10);</span><br><span class="line"> boolean isTimeout = randomTimeout > 8 ? true : false;</span><br><span class="line"> if (isTimeout) {</span><br><span class="line"> System.out.println("timeout " + randomTimeout + ", cancel job.");</span><br><span class="line"> futureTask.cancel(true);</span><br><span class="line"> break;</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line">if (futureTask.isCancelled()) {</span><br><span class="line"> System.out.println("cancelled, isDone: " + futureTask.isDone() + ". " + Thread.currentThread().getName());</span><br><span class="line">} else {</span><br><span class="line"> System.out.println("isDone: " + futureTask.isDone() + ", result: " + futureTask.get() + ". " + Thread.currentThread().getName());</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>When we initialize the FutureTask, it accepts a Callable task which is the task to be executed asynchronously. Then we create a thread for the FutureTask, and internally it will call the Callable task. <code>futureTask.isDone()</code> checks the current running task status, and if the task is completed, return true. In our use case, if it’s timeout, <code>futureTask.cancel(true)</code> attempts to cancel execution of this task. Finally <code>futureTask.get()</code> fetches result from the Callable task.</p>
<p><code>CompletableFuture</code><br>CompletableFuture is one of implementations of the Future interface. It has been introduced by JDK 1.8, so those methods of CompletableFuture are easily integrated with the functional interfaces. CompletableFuture provide a very easy way to chain those async tasks together as a complex async tasks pipeline.<br>a. <code>CompletableFuture basic methods</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">CompletableFuture<String> futureAsyncTask = CompletableFuture.supplyAsync(() -> {</span><br><span class="line"> try {</span><br><span class="line"> System.out.println("do something");</span><br><span class="line"> Thread.sleep(1000);</span><br><span class="line"> } catch (InterruptedException e) {</span><br><span class="line"> e.printStackTrace();</span><br><span class="line"> }</span><br><span class="line"> return "ok";</span><br><span class="line">});</span><br><span class="line">System.out.println(futureAsyncTask.getNow("not_found"));</span><br><span class="line">System.out.println(futureAsyncTask.join());</span><br></pre></td></tr></table></figure></p>
<p><code>CompletableFuture.supplyAsync()</code> accepts a Supplier functional interface which defines the task. Once the CompletableFuture is created, the task will be running in a seperated thread. <code>futureAsyncTask.getNow("not_found")</code> fetches the result from the task, and if the task is not completed, return the default result which is the arguments. <code>futureAsyncTask.join()</code> makes the main thread synchronized to wait and fetch the result until the async task is completed. The join() method is similar to the get() method, but join() method does not require to catch the checked Exception which may be throwed in the seperated thread specifically in the main thread. Here is one more example below.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">List<String> visitList = Arrays.asList("Lasha", "Linzhi", "Yangzhuoyongcuo", "Yaluzangbujiang");</span><br><span class="line">List<CompletableFuture<String>> futureAsyncTaskList = visitList.stream()</span><br><span class="line"> .map((String visit) -> CompletableFuture.supplyAsync(() -> {</span><br><span class="line"> Random r = new Random();</span><br><span class="line"> int time = (r.nextInt(5) + 1) * 1000;</span><br><span class="line"> try {</span><br><span class="line"> Thread.sleep(time);</span><br><span class="line"> } catch (InterruptedException e) {</span><br><span class="line"> e.printStackTrace();</span><br><span class="line"> }</span><br><span class="line"> return String.format("visit %s for %d hours, async task %s", visit, time/1000, Thread.currentThread().getName());}))</span><br><span class="line"> .collect(Collectors.toList());</span><br><span class="line">try {</span><br><span class="line"> Thread.sleep(4000);</span><br><span class="line">} catch (InterruptedException e) {</span><br><span class="line"> e.printStackTrace();</span><br><span class="line">}</span><br><span class="line">futureAsyncTaskList.stream().map((CompletableFuture<String> task) -> task.getNow("not_ready")).forEach((String plan) -> System.out.println(plan));</span><br></pre></td></tr></table></figure></p>
<p>b. <code>Compare with Executors</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">ExecutorService es = Executors.newCachedThreadPool();</span><br><span class="line">List<Future<String>> futureList = visitList.stream()</span><br><span class="line"> .map((String visit) -> es.submit(() -> {</span><br><span class="line"> Random r = new Random();</span><br><span class="line"> int time = (r.nextInt(5) + 1) * 1000;</span><br><span class="line"> try {</span><br><span class="line"> Thread.sleep(time);</span><br><span class="line"> } catch (InterruptedException e) {</span><br><span class="line"> e.printStackTrace();</span><br><span class="line"> }</span><br><span class="line"> return String.format("visit %s for %d hours, async task %s", visit, time/1000, Thread.currentThread().getName());}))</span><br><span class="line"> .collect(Collectors.toList());</span><br><span class="line">futureList.stream().map((Future<String> task) -> {</span><br><span class="line"> try {</span><br><span class="line"> return task.get();</span><br><span class="line"> } catch (InterruptedException e) {</span><br><span class="line"> e.printStackTrace();</span><br><span class="line"> } catch (ExecutionException e) {</span><br><span class="line"> e.printStackTrace();</span><br><span class="line"> }</span><br><span class="line"> return null;</span><br><span class="line">}).forEach((String plan) -> System.out.println(plan));</span><br></pre></td></tr></table></figure></p>
<p>c. <code>CompletableFuture advanced features</code><br>As we mentioned earlier, CompletableFuture can build the complex future tasks pipeline.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">CompletableFuture<String> futureWhenCompleteTask0 = CompletableFuture.supplyAsync(() -> {</span><br><span class="line"> try {</span><br><span class="line"> System.out.println("do something futureWhenCompleteTask0");</span><br><span class="line"> Thread.sleep(1000);</span><br><span class="line"> } catch (InterruptedException e) {</span><br><span class="line"> e.printStackTrace();</span><br><span class="line"> }</span><br><span class="line"> return "Singapore";</span><br><span class="line">});</span><br></pre></td></tr></table></figure></p>
<p>c.1 <code>whenComplete()</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">CompletableFuture<String> futureWhenCompleteTask1 = futureWhenCompleteTask0.whenComplete((String result, Throwable e) -> {</span><br><span class="line"> try {</span><br><span class="line"> System.out.println("do something futureWhenCompleteTask1");</span><br><span class="line"> Thread.sleep(1000);</span><br><span class="line"> } catch (InterruptedException e1) {</span><br><span class="line"> e1.printStackTrace();</span><br><span class="line"> }</span><br><span class="line"> System.out.println(String.format("now: %s -> future: China", result));</span><br><span class="line">});</span><br><span class="line">System.out.println("futureWhenCompleteTask1 final result: " + futureWhenCompleteTask1.join());</span><br></pre></td></tr></table></figure></p>
<p>When futureWhenCompleteTask0 stage is completed, taking the result of first stage, the given action of futureWhenCompleteTask1 is getting called. But eventually the futureWhenCompleteTask1 result is still from futureWhenCompleteTask0, and the action of futureWhenCompleteTask1 can be considerd as the additional action after futureWhenCompleteTask0 produces result, because whenComplete() takes a BiConsumer as the action. Console log, now: Singapore -> future: China, futureWhenCompleteTask1 final result: Singapore.<br>c.2 <code>thenApply()</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">CompletableFuture<String> futureWhenCompleteTask2 = futureWhenCompleteTask0.thenApply((String result) -> {</span><br><span class="line"> try {</span><br><span class="line"> System.out.println("do something futureWhenCompleteTask2");</span><br><span class="line"> Thread.sleep(1000);</span><br><span class="line"> } catch (InterruptedException e1) {</span><br><span class="line"> e1.printStackTrace();</span><br><span class="line"> }</span><br><span class="line"> System.out.println(String.format("now: %s -> future: China", result));</span><br><span class="line"> return String.format("now: %s -> future: China", result);</span><br><span class="line">});</span><br><span class="line">System.out.println("futureWhenCompleteTask2 final result: " + futureWhenCompleteTask2.join());</span><br></pre></td></tr></table></figure></p>
<p>Compare with the whenComplete() method, due to thenApply() taking a java.util.function.Function, thenApply() method returns the computed result. Console log, now: Singapore -> future: China, futureWhenCompleteTask2 final result: now: Singapore -> future: China.<br>c.3 <code>thenCompose()</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">CompletableFuture<String> futureWhenCompleteTask3 = futureWhenCompleteTask0.thenCompose((String result) -> </span><br><span class="line"> CompletableFuture.supplyAsync(() -> result + " -> Chengdu"));</span><br><span class="line">System.out.println("futureWhenCompleteTask3 final result: " + futureWhenCompleteTask3.join());</span><br></pre></td></tr></table></figure></p>
<p>Console log, futureWhenCompleteTask3 final result: Singapore -> Chengdu.<br>c.4. <code>thenCombine()</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">CompletableFuture<String> futureWhenCompleteTask4 = futureWhenCompleteTask2.thenCombine(</span><br><span class="line"> CompletableFuture.supplyAsync(() -> "-Chengdu"), (String t2, String t4) -> t2 + t4);</span><br><span class="line">System.out.println("futureWhenCompleteTask4 final result: " + futureWhenCompleteTask4.join());</span><br></pre></td></tr></table></figure></p>
<p>futureWhenCompleteTask4 and futureWhenCompleteTask2 run concurrently, once both of the two tasks are completed, it returns the computed result. Console log, futureWhenCompleteTask4 final result: now: Singapore -> future: China-Chengdu.<br>c.5 more methods<br><code>thenAccept()</code>, <code>allOf()</code> (similar to CountDownLatch or CyclicBarrier), <code>anyOf()</code>, etc.<br>d. <code>why was CompletableFuture introduced by JDK 1.8?</code><br>As mentioned above, CompletableFuture provide a very easy way to build the complex future tasks pipeline such as IO tasks. Its default thread pool is ForkJoinPool which of the pool size is based on CPU cores. CompletableFuture provides multiple methods for pipeline such as whenComplete, thenApply, thenCompose, thenCombine, allOf, anyOf, etc.<br>e. <code>Additional knowledge, thread pool size</code><br>CPU denseness task: thread pool size should be based on CPU cores.<br>IO intensive task: thread pool size should be based on CPU cores <em> CPU utilization ratio </em> (1 + thread waiting time/thread CPU holding time).<br>In summary, regarding the IO operations, the default ForkJoinPool cannot get the best performance, and the customized thread pool is recommended.</p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/01/19/Concurrency-高并发-CountDownLatch-and-CyclicBarrier/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="Xu Lei">
<meta itemprop="description" content="">
<meta itemprop="image" content="https://avatars2.githubusercontent.com/u/7018287">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="Xu Lei's Techblog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2020/01/19/Concurrency-高并发-CountDownLatch-and-CyclicBarrier/" itemprop="url">Concurrency 高并发 - CountDownLatch and CyclicBarrier</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2020-01-19T00:00:00+08:00">
2020-01-19
</time>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p><em>Use Case 1</em>: checkout of the shopping cart, calling merchant downstream services concurrently to get and confirm the latest bills, once confirm the total amount, calling multiple payment gateway APIs concurrently to get all the available payment approaches with enough balance.<br><em>Use Case 2</em>: running race, 3 times, the winner is the one who get the minimum of time in total.</p>
<p>There are some use cases which require the running threads in certain order. CountDownLatch and CyclicBarrier are the tools to allow those threads waiting for each other.</p>
<p><em>Sample code: <em>com.snippet.concurrent</em> and <em>com.snippet.test.concurrent</em> of the Snippets repository in <a href="https://github.com/xljiadahao/Snippets.git" target="_blank" rel="noopener">GitHub</a>.</em></p>
<p><code>CountDownLatch</code><br>Thread groups are waiting for each other within multiple thread groups.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public class Player extends Thread {...}</span><br><span class="line"></span><br><span class="line">CountDownLatch latch = new CountDownLatch(4);</span><br><span class="line">new Player(latch, "merchant1").start();</span><br><span class="line">new Player(latch, "merchant2").start();</span><br><span class="line">new Player(latch, "merchant3").start();</span><br><span class="line">new Player(latch, "merchant4").start();</span><br><span class="line">latch.await();</span><br><span class="line"></span><br><span class="line">System.out.println("countinue to do something else such as calling payment gateway");</span><br></pre></td></tr></table></figure></p>
<p>The sample code above shows that it starts 4 threads concurrently, registers a CountDownLatch to count the 4 threads, and sets a barrier until all of the 4 running threads are finished.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public class Player extends Thread {</span><br><span class="line"> ...</span><br><span class="line"> @Override</span><br><span class="line"> public void run() {</span><br><span class="line"> ...complete the task...</span><br><span class="line"> latch.countDown();</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>Once each thread completes the task, at the end it calls <code>latch.countDown()</code> to count down or -1 of the CountDownLatch. CountDownLatch will remove the barrier of the thread group when the count of CountDownLatch == 0, then the main thread could continue to execute the rest of the code.</p>
<p><code>CyclicBarrier</code><br>Threads are waiting for each other within a single thread group. It can be recycling used.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">private int currentTime = 0;</span><br><span class="line">private int maximumScore = 0;</span><br><span class="line">private boolean isOngoing = true;</span><br><span class="line">private Map<String, Integer> scoreboard = new ConcurrentHashMap<>();</span><br><span class="line"></span><br><span class="line">CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> {</span><br><span class="line"> System.out.println("CyclicBarrier executed, round " + ++currentTime);</span><br><span class="line"> isOngoing = true;</span><br><span class="line"> if (currentTime >= 4) {</span><br><span class="line"> scoreboard.entrySet().stream().sorted((Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) -> o1.getValue() == o2.getValue() ? 0 : (o1.getValue() > o2.getValue() ? -1 : 1)).forEach((Map.Entry<String, Integer> runner) -> {</span><br><span class="line"> if (runner.getValue() >= maximumScore) {</span><br><span class="line"> maximumScore = runner.getValue();</span><br><span class="line"> System.out.println("Announce Final Winner: " + runner.getKey() + ", winning times: " + runner.getValue());</span><br><span class="line"> } </span><br><span class="line"> });</span><br><span class="line"> }</span><br><span class="line">});</span><br></pre></td></tr></table></figure></p>
<p>Define a CyclicBarrier, here are two parameters of the one of constructors:<br>a. parties the number of threads that must invoke await before the barrier is tripped.<br>b. barrierAction the command to execute when the barrier is tripped, or null if there is no action.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">for (int i = 0; i < 3; i++) {</span><br><span class="line"> new Thread(()->{</span><br><span class="line"> scoreboard.put(Thread.currentThread().getName(), 0);</span><br><span class="line"> while (currentTime < 4) {</span><br><span class="line"> try {</span><br><span class="line"> Thread.sleep(new Random().nextInt(5) * 1000);</span><br><span class="line"> System.out.println(Thread.currentThread().getName() + " reached barrier.");</span><br><span class="line"> updateWinnerStatus(Thread.currentThread().getName());</span><br><span class="line"> cyclicBarrier.await();</span><br><span class="line"> } catch (InterruptedException e) {</span><br><span class="line"> e.printStackTrace();</span><br><span class="line"> } catch (BrokenBarrierException e) {</span><br><span class="line"> e.printStackTrace();</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }, "runner" + i).start(); </span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">// pessimism lock</span><br><span class="line">private synchronized void updateWinnerStatus(String runner) {</span><br><span class="line"> if (isOngoing) {</span><br><span class="line"> scoreboard.put(runner, scoreboard.get(runner) + 1);</span><br><span class="line"> System.out.println("winner: " + runner);</span><br><span class="line"> isOngoing = false;</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>In each thread, <code>cyclicBarrier.await()</code> will be called. Once the <code>await()</code> of all the 3 threads are called, each thread of those 3 can continue execute the rest of the code. CyclicBarrier is getting reset and it can be resued again.</p>
<p><code>CountDownLatch vs CyclicBarrier</code><br>a. In general, thread groups are waiting for each other, use CountDownLatch; within a group of threads, each thread is waiting for each other, use CyclicBarrier.<br>b. CountDownLatch is counting –, while CyclicBarrier is counting ++.<br>c. CountDownLatch can be used when the count reached 0 and it cannot be reset, while CyclicBarrier can be reset each time, reused multiple times.</p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/04/15/Xu-Lei-Showcase-Super-App-Seamless-Payment-Framework-Prototype/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="Xu Lei">
<meta itemprop="description" content="">
<meta itemprop="image" content="https://avatars2.githubusercontent.com/u/7018287">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="Xu Lei's Techblog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2018/04/15/Xu-Lei-Showcase-Super-App-Seamless-Payment-Framework-Prototype/" itemprop="url">Xu Lei Showcase - Seamless Super App Prototype</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-15T00:00:00+08:00">
2018-04-15
</time>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>(<em><code>Declare: the Seamless Super App Prototype is my personal project, and it does not have any relationship with PayPal. I will remove the PayPal logo very soon.</code></em>)<br>Note: The size of the demo video is about 100MB, so it could be better to watch it in the <code>WiFi</code> network environment. The demo video is tested against the Chrome, Firefox and Safari browers in Mac. You can stop to watch it by operating the video control panel. Demo steps: 1. Scan McDonald’s QR code for seamless payment, 2. Scan Pizza Hut QR code for seamless payment.</p>
<table><tr><th bgcolor="grey"><center>Scan to Pay for McDonald’s</center></th><th bgcolor="grey"><center>Scan to Pay for Pizza Hut</center></th></tr><tr><td height="510"><video src="/videos/superapp/PayPalQR_McD.mov" width="100%" height="100%" poster="/images/superapp/poster.png" autoplay="autoplay" controls="controls">Your browser or system may not support the media. Please use latest version of Chrome, Firefox or Safari in Mac.</video></td><td height="510"><video src="/videos/superapp/PayPalQR_PizH.mov" width="100%" height="100%" poster="/images/superapp/poster.png" autoplay="autoplay" controls="controls">Your browser or system may not support the media. Please use latest version of Chrome, Firefox or Safari in Mac.</video></td></tr></table>
<p>##Concept<br><code>Super App</code><br>Super App means opening for Integration, Integration and Integration!!!<br>(Refer to WeChat Little Program concept) The future apps allow users <code>Use and Leave</code> without downloading.<br><code>Seamless Authentication User Experience</code><br>Seamless Login for the Authenticated User. For example, the users logged in their mobile app, they can use the system anywhere such as mobile, web app at laptop, and so forth.<br>Blur the lines of payment between online and offline.<br>Blur the lines between different systems.</p>
<p>##Design<br><img src="/images/superapp/logic_view.png" alt="logic view" title="logic view"><br><img src="/images/superapp/physical_view.png" alt="physical view" title="physical view"></p>
<p>##Security</p>
<table><tr><th width="25%" bgcolor="grey"><center>Security Concern</center></th><th bgcolor="grey"><center>Security Challenge</center></th><th bgcolor="grey"><center>Solution</center></th></tr><tr><td bgcolor="#eeeeee"> QR Code </td><td> The QR code is able to contain any information, valid or invalid. It will be risky to redirect user to the invalid site. </td><td> <code>Tokenized QR Code</code> signed by the payment gateway (here is JWT, Json Web Token). <code>HMAC</code> digital signature within the token ensures token can be verified by issuer only, and no one is able to change the token information as only the payment gateway hold the HMAC signature key. </td></tr><tr><td bgcolor="#eeeeee"> Payment Process </td><td> Merchants should not play the role to conduct the payment process. For example, user buy $10 product, merchant might internally ask the payment gateway to charge the user $100 intently or by mistake. </td><td> Merchant site <code>natively direct the payment process to the payment gateway mobile app to allow users confirm the payment within the payment app</code>. (Android prototype tech challenge: child thread call redirect to main thread). User is able to make a final verification of their payment detail before clicking the pay button. Payment gateway will fully control the payment process securely. </td></tr><tr><td bgcolor="#eeeeee"> Payment Status Notification </td><td> For the merchant perspective, it’s not secure to allow any client to notify and change the payment status. </td><td> By design, the merchant portal just allows payment gateway as the payment authority to notify the payment result. Merchant will generate the receipt based on the payment status for the specific order. </td></tr></table>
<p>##Extension<br>a. Seamless authentication. I am an authenticated user at the mobile app. I should be able to seamlessly get authenticated at my iPad app, Desktop Web System wherever I am required to be authenticated. SSO, single sign on, to be the legal entity in the system cross platforms, QR code can bridge the gap.<br>b. Seamless authorization with payment. Merchants generate the bill online and users just need to open the payment app, Scan the QR code on the web page and Pay. Blur the lines between the payment gateway and the merchant site. Username and Password are old days for authorization and authentication. Inconvenient and high risk to enter the credential through merchant site due to phishing sites.<br>c. Order ahead. For those used merchant tokens, they can be stored as the history or shortcut for the next time order ahead capability.<br>d. Default integration with verified government sites. User can easily pay for their tax, water bill, phone bill, and so forth. Scenario payment to change user’s daily lives, and increase DAU (Daily Active User).<br>e. Integration with loyalty systems, restaurant bookings, advance paying for carpark to reserve it before you reaching the place, paying for season parking, etc.</p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/03/12/Json-Web-Token-JWT/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="Xu Lei">
<meta itemprop="description" content="">
<meta itemprop="image" content="https://avatars2.githubusercontent.com/u/7018287">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="Xu Lei's Techblog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2018/03/12/Json-Web-Token-JWT/" itemprop="url">Json Web Token (JWT)</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2018-03-12T00:00:00+08:00">
2018-03-12
</time>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>Json Web Token (JWT) plays a signifiant role as the secure identity, especially in the distributed architecure such as SOA (Service Oriented Architecture) systems. Here I would like to introduce JWT by the following steps. 1. Brief introduction of JWT, 2. Benefit of JWT, 3. Sample implementation to use JWT in Java.</p>
<p>a. <code>Brief introduction of JWT</code><br>I would like to introduce JWT briefly. JWT is a secure information transmitting way based on the open standard (RFC 7519) by a json object. It contains 3 parts, Header, Payload, Signature seperated by dots (.). Therefore, a typical JWT token looks like the following format. <code>Header.Payload.Signature</code>. Let’s break down to get the details of each part.<br>Header<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">{</span><br><span class="line"> "alg": "HS256",</span><br><span class="line"> "typ": "JWT"</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>The header generally consists of two parts: the type of the token, and the hashing algorithm being used. Then it will be getting base64 encoded to form the header part of the JWT.<br>Note: <code>Encoding is the public known way to tranfer the data from one format to another format.</code> Therefore, the header is getting base64 encoded, which means the header part of JWT can be considered as the <code>plain text</code>. Thus, we should NOT store the sensitive information in the JWT header.<br>Payload<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">{</span><br><span class="line"> "sub": "third party authorization",</span><br><span class="line"> "iss": "auth0",</span><br><span class="line"> "exp": "1520239160663"</span><br><span class="line"> "customclaims": </span><br><span class="line"> {</span><br><span class="line"> "id": 33,</span><br><span class="line"> "userName": "lei",</span><br><span class="line"> "role": </span><br><span class="line"> {</span><br><span class="line"> "roleName": "admin",</span><br><span class="line"> "privileges": ["read", "write", "delete"]</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>Payload contains three types of claims: registered, public, and private claims. They are statements about an entity. Registered claims are a set of predefined claims with three characters claim name such as iss (issuer), exp (expiration time), sub (subject), aud (audience). Public claims can be defined at will by those using JWTs. Private claims are the custom claims for information sharing between parties like “customclaims” in the sample above. Then it will be getting base64 encoded to form the payload part of the JWT.<br>Note: Similar to JWT header, the payload is getting base64 encoded, which means the payload part of JWT can be considered as the <code>plain text</code>. Thus, we should NOT store the sensitive information in the JWT payload.<br>Signature<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">HMACSHA256(</span><br><span class="line"> base64UrlEncode(header) + "." +</span><br><span class="line"> base64UrlEncode(payload),</span><br><span class="line"> secret)</span><br></pre></td></tr></table></figure></p>
<p>Use the algorithm specified in the header to sign the encoded header, the encoded payload with a secret. The signature is used to verify the message wasn’t changed along the way. In the sample, we use HMAC SHA256 algorithm.<br>Note: <code>Signature typically takes use of hash function which is one way encryption.</code> It cannot be reverted back to get the secret by the signature. Any information in the token is getting changed, then it will result in generating different signature for the failed verification. Thus, the <code>secret</code> is very important for the verification, and it will be stored in the <code>server side</code> only securely. <code>During verification, the server will re-caculate the singature by first two parts of the JWT, the base64 encoded header and the base64 encoded payload, with the secret which is only known by the server, then compare the re-caculated signature with the sigature of the JWT</code>.<br>Json Web Token (JWT)<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsInN1YiI6InRoaXJkIHBhcnR5IGF1dGhvcml6YXRpb24iLCJjdXN0b21jbGFpbXMiOiJ7XCJpZFwiOjMzLFwidXNlck5hbWVcIjpcImxlaVwiLFwicm9sZVwiOntcInJvbGVOYW1lXCI6XCJhZG1pblwiLFwicHJpdmlsZWdlc1wiOltcInJlYWRcIixcIndyaXRlXCIsXCJkZWxldGVcIl19fSIsImV4cCI6MTUyMDcxNTcwODAzOH0.om5ZNtXDtsp6IUOErHcrE1kykiNEebjA55QCmxdWxnk</span><br></pre></td></tr></table></figure></p>
<p>Therefore, the JWT like the sample above is the combination of the base64 encoded header, the base64 encoded payload, and the signiture signed with a secret.<br>Again, do note that with signed tokens, all the information contained within the token is exposed to users or other parties, even though they are unable to change it. This means you should not put secret information within the token.<br>As the general flow to use the JWT token, the user will login with the credential to get a JWT token, then the user can take use of the JWT token to access the protected resources. To find out more information about Json Web Token (JWT) or try out JWT token generation, decoding and verification online, browse the <a href="https://jwt.io/" target="_blank" rel="noopener">jwt.io</a> website.</p>
<p>b. <code>Benefit of JWT</code><br>1 High efficiency. The server do not need to have the database access for authentication, and instead, it just need to re-caculate the signature in memory for verification.<br>2 Cross-Origin Resource Sharing. JWT token provides the stateless way for authentication, so it could not be an issue to access the resources cross multiple services as it doesn’t use cookie and session, especially for the distributed architecture systems.<br>3 Light weight. JWT is a light weight format transmitting way between parties by the http request (mostly in the http header). It can exchange the necessary information within the JWT payload.</p>
<p>c <code>Sample implementation to use JWT in Java</code><br>Here we use auth0 library for the implementation.<br>pom.xml<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><dependency></span><br><span class="line"> <groupId>com.auth0</groupId></span><br><span class="line"> <artifactId>java-jwt</artifactId></span><br><span class="line"> <version>2.2.1</version></span><br><span class="line"></dependency></span><br></pre></td></tr></table></figure></p>
<p>Signing with a secret, return the JWT token as a String<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">public static<T> String sign(T object, long maxAge) throws Exception {</span><br><span class="line"> final JWTSigner signer = new JWTSigner(SECRET);</span><br><span class="line"> final Map<String, Object> claims = new HashMap<String, Object>();</span><br><span class="line"> ObjectMapper mapper = new ObjectMapper();</span><br><span class="line"> String jsonString = mapper.writeValueAsString(object);</span><br><span class="line"> claims.put(CUSTOM_CLAIMS, jsonString);</span><br><span class="line"> claims.put(EXPIRATION_TIME, System.currentTimeMillis() + maxAge);</span><br><span class="line"> claims.put(ISSUER, "auth0");</span><br><span class="line"> claims.put(SUBJECT, "third party authorization");</span><br><span class="line"> return signer.sign(claims);</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>Unsigning with the same secret by signature verification<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">public static<T> T unsign(String jwt, Class<T> classT) throws Exception {</span><br><span class="line"> final JWTVerifier verifier = new JWTVerifier(SECRET);</span><br><span class="line"> final Map<String,Object> claims= verifier.verify(jwt);</span><br><span class="line"> if (claims.containsKey(EXPIRATION_TIME) && claims.containsKey(ISSUER) </span><br><span class="line"> && claims.containsKey(SUBJECT) && claims.containsKey(CUSTOM_CLAIMS)) {</span><br><span class="line"> long exp = (long) claims.get(EXPIRATION_TIME);</span><br><span class="line"> System.out.println("EXPIRATION_TIME: " + sdf.format(new Date(exp)) + ", ISSUER: " </span><br><span class="line"> + (String) claims.get(ISSUER) + ", SUBJECT: " + (String) claims.get(SUBJECT));</span><br><span class="line"> if (exp > System.currentTimeMillis()) {</span><br><span class="line"> String privateClaims = (String) claims.get(CUSTOM_CLAIMS);</span><br><span class="line"> ObjectMapper objectMapper = new ObjectMapper();</span><br><span class="line"> return objectMapper.readValue(privateClaims, classT);</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> return null;</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>Find more about the code snippets of JWT under the package <em>com.snippet.jwt</em> of the Snippet repository in <a href="https://github.com/xljiadahao/SnippetInnovationWithSpringBoot.git" target="_blank" rel="noopener">GitHub</a>.</p>
<p>The code snippets demo for the JWT token generation and verification.</p>
<p>1 login to get the JWT token within hateoas link<br><img src="/images/jwt/jwt_login_request.png" alt="request of token generation" title="request for token generation"><br><img src="/images/jwt/jwt_login_response.png" alt="response of token generation" title="response of token generation"><br>2 verify the token by getting the user information<br><img src="/images/jwt/jwt_verify_request_response.png" alt="token verification" title="token verification"></p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/02/04/Java-8-Features/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="Xu Lei">
<meta itemprop="description" content="">
<meta itemprop="image" content="https://avatars2.githubusercontent.com/u/7018287">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="Xu Lei's Techblog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2018/02/04/Java-8-Features/" itemprop="url">Java 8 Features</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2018-02-04T00:00:00+08:00">
2018-02-04
</time>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>I would like to introduce the Java 8 features in a systematic way. Basically, Java 8 introduces the following new features. 1. functional interface, 2. lambda expression, 3. 6 types of pre-defined functional interface in Java 8, 4. stream API, 5. default method, 6. effective final, 7. method reference.</p>
<p>a. <code>Functional Interface</code><br>Functional Interface is a single abstract method interface.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">@FunctionalInterface</span><br><span class="line">public interface Payment {</span><br><span class="line"> public void pay(ShoppingCart shoppingCart, </span><br><span class="line"> Predicate<Integer> isReceiptRequired);</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>The annotation <em>FunctionalInterface</em> checks against the class to comply with the rule of functional interface that it is a single abstract method interface. If we introduce another abstract method in the class, there will be compile error.</p>
<p>b. <code>Lambda Expression</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public void checkout() {</span><br><span class="line"> Payment cashPay = (ShoppingCart shoppingCart, </span><br><span class="line"> Predicate<Integer> isReceiptRequired) -> {</span><br><span class="line"> System.out.println("Cash is NOT support");</span><br><span class="line"> };</span><br><span class="line"> cashPay.pay(getShoppingCart(), (Integer amount) -> false);</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>Lambda Expression can be only used for Functional Interface. It uses the syntax <em>-></em> to indicate the method body of the single abstract method interface. The left side of <em>-></em> is the method parameters, and the right side of <em>-></em> is the method implementation.</p>
<p>c. <code>6 Types of Functional Interface in Java 8</code><br>They are all under the package <em>java.util.function</em>.<br>A. <em>Predicate, (I) -> boolean, replace if else</em><br>B. <em>Function, (I) -> R, transformer, one type to another type</em><br>C. <em>Consumer, (I) -> void, consumer the input data</em><br>D. <em>Supplier, () -> new (), factory pattern</em><br>E. <em>BinaryOperator, (I, I) -> I, reducers, accumulation</em><br>F. <em>UnaryOperator, (I) -> I</em><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">public default Optional<Integer> calculateTotalAmount(ShoppingCart shoppingCart) {</span><br><span class="line"> Predicate<Product> filterCondition = (Product p) -> </span><br><span class="line"> StringUtils.isNotBlank(p.getId()) && p.getPrice() > 0;</span><br><span class="line"> Function<Product, Integer> mapToPrice = (Product p) -> p.getPrice() * p.getQuantity();</span><br><span class="line"> BinaryOperator<Integer> reduceCheckoutAmount = </span><br><span class="line"> (Integer price0, Integer price1) -> price0 + price1;</span><br><span class="line"> /**</span><br><span class="line"> * stream (for Collections) 1. filter, 2. map, 3. reduce.</span><br><span class="line"> * fork join pool with concurrent processing</span><br><span class="line"> */</span><br><span class="line"> return shoppingCart.getProducts().stream().parallel()</span><br><span class="line"> .filter(filterCondition).map(mapToPrice).reduce(reduceCheckoutAmount);</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>Here we have 3 examples for Predicate, Function, BinaryOperator functional interfaces respectively. They are all functional interfaces, so we can represent the method body as the lambda expression.<br><em>Predicate</em> is a functional interface which has a single method of return type boolean. The method implementation <em>StringUtils.isNotBlank(p.getId()) && p.getPrice() > 0</em> will be either true or false. By the way, the <em>return</em> key word can be omitted for the lambda expression approach.<br><em>Function</em> is a functional interface which has a single method of one type input, the different type of output. <em>(Product p) -> p.getPrice() * p.getQuantity();</em>, input is Product, but output is String which is different from the input type.<br><em>BinaryOperator</em> is a functional interface which has a single method of two inputs and one output with the same type. It is similar to the <em>reduce</em> of the map-reduce concept, generally for accumulation. <em>(Integer price0, Integer price1) -> price0 + price1;</em>, two integers as the input, the output is an integer of the sum of the two input integers.</p>
<p>d. <code>Stream API</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">public default String printReceipt(ShoppingCart shoppingCart) {</span><br><span class="line"> StringBuilder receipt = new StringBuilder();</span><br><span class="line"> SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");</span><br><span class="line"> for(Category category : Category.values()) {</span><br><span class="line"> receipt.append("$$$$$$$$$").append(category.name()).append("$$$$$$$$$").append("\n");</span><br><span class="line"> shoppingCart.getProducts().stream()</span><br><span class="line"> .filter((Product p) -> p.getCategory() == category).sorted((Product o1, Product o2) </span><br><span class="line"> -> o1.getId().equals(o2.getId()) ? 0 : (o1.getPrice() > o2.getPrice() ? 1 : -1))</span><br><span class="line"> .forEach((Product p) -> receipt.append(p.getId()).append(" ").append(p.getName())</span><br><span class="line"> .append(" ").append("X").append(p.getQuantity()).append(" ").append("SGD")</span><br><span class="line"> .append(p.getPrice()).append("\n"));</span><br><span class="line"> }</span><br><span class="line"> receipt.append("^^^^^^^^^^^^^^^^^^^^").append("\n");</span><br><span class="line"> receipt.append("Checkout Total Amount: ").append(calculateTotalAmount(shoppingCart).get())</span><br><span class="line"> .append(" SGD").append("\n");</span><br><span class="line"> receipt.append("Transaction Time: ").append(sdf.format(new Date())).append("\n");</span><br><span class="line"> return receipt.toString();</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>For collections, <em>Stream API</em> allows to iterate each item of the collection, and enqueue each item within the pipeline to process, such as filter, for-each, map-reduce.<br><em>shoppingCart.getProducts().stream()</em>, it iterates the list of Product as the stream pipeline, moreover, <em>parallel()</em> will take use of the fork join pool for concurrent processing, then calls the corresponding stream API (the functional interfaces play the role like the anonymous inner class, but they are different in their underline behaviours), filter which input is a Predicate, (see the code in section c) map which input is a Function, reduce which input is a BinaryOperator, and so forth.</p>
<p>e. <code>Default Method</code><br>The code snippet in section c and section d has the method with the <em>default</em> key word. Before Java 8 release, in the interface, we can just define the abstract methods as the contract, and the class which implements the interface has the concrete implementation of the interface method.<br>Java 8 introduces the default method in the interface class for the default implementation.</p>
<p>f. <code>Effective Final</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">public void checkout() {</span><br><span class="line"> System.out.println("---------Checkout with Cash---------");</span><br><span class="line"> int cash = 10;</span><br><span class="line"> Payment cashPay = (ShoppingCart shoppingCart, Predicate<Integer> isReceiptRequired) -> {</span><br><span class="line"> /**</span><br><span class="line"> * cannot change, effective final;</span><br><span class="line"> * local variable for lambda expression, auto change to final variable.</span><br><span class="line"> * </span><br><span class="line"> * cash = 2000;</span><br><span class="line"> */</span><br><span class="line"> System.out.println("Cash is NOT support");</span><br><span class="line"> };</span><br><span class="line"> cashPay.pay(getShoppingCart(), (Integer amount) -> false);</span><br><span class="line"> System.out.println();</span><br><span class="line"> System.out.println("---------Checkout with Cashlessa 8---------");</span><br><span class="line"> payment.pay(getShoppingCart(), this::isAskingReceipt);</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>Local variable for lambda expression, it will be automatically changed to final variable.<br>In this example, the local variable int cash cannot be modified within the lambda expression (cash = 2000) as it is changed to the final variable automatically. Otherwise, there will be compile error in line 9 (code snippet in section f).</p>
<p>g. <code>Method Reference</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public void checkout() {</span><br><span class="line"> ...</span><br><span class="line"> /**</span><br><span class="line"> * method reference</span><br><span class="line"> */</span><br><span class="line"> payment.pay(getShoppingCart(), this::isAskingReceipt);</span><br><span class="line">}</span><br><span class="line">private boolean isAskingReceipt(Integer amount) {</span><br><span class="line"> return amount > 10;</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>In java 8, we can use the syntax <em>::</em> to refer a method body.<br>In this example, the second input of the pay method is a Predicate. Here we use the method reference to indicate the method body which is the implemetation of the Predicate.</p>
<p>In summary, Java 8 provides us some flexible ways to return the complex logic within one line, and more significant, it introduces the concept of Functional Interface for the functional programming pattern.</p>
<p>The code snippets above are under the package <em>com.snippet.java8.feature</em> of the Snippets repository in <a href="https://github.com/xljiadahao/Snippets.git" target="_blank" rel="noopener">GitHub</a>. Feel free to create any GitHub issues against the repository if you have any questions or you want to correct the code snippet errors based on your understanding. Welcome.</p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/01/14/Hello-Hexo/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="Xu Lei">
<meta itemprop="description" content="">
<meta itemprop="image" content="https://avatars2.githubusercontent.com/u/7018287">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="Xu Lei's Techblog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2018/01/14/Hello-Hexo/" itemprop="url">Hello 你好 Hexo</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-14T17:42:03+08:00">
2018-01-14
</time>
</span>
<span class="post-category" >
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/blog/" itemprop="url" rel="index">
<span itemprop="name">blog</span>
</a>
</span>
</span>