-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03-devlink-fastexcel.html
More file actions
894 lines (666 loc) · 39.5 KB
/
Copy path03-devlink-fastexcel.html
File metadata and controls
894 lines (666 loc) · 39.5 KB
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
<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>
<head>
<meta charset="UTF-8">
<link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
<link rel="icon" href="/img/fluid.png">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="theme-color" content="#2f4154">
<meta name="author" content="Cassiur">
<meta name="keywords" content="Java">
<meta name="description" content="DevLink③:FastExcel 并发导出 + 线程池调优(完整版) @page { size: A4; margin: 20mm 18mm 20mm 18mm; @top-center { content: "DevLink③ FastExcel 并发导出"; font-size: 9pt; color: #666; } @bottom-center { co">
<meta property="og:type" content="website">
<meta property="og:title" content="page.title">
<meta property="og:url" content="https://whyalwaysme.lol/03-devlink-fastexcel.html">
<meta property="og:site_name" content="WhyAlwaysMe 的树洞">
<meta property="og:description" content="DevLink③:FastExcel 并发导出 + 线程池调优(完整版) @page { size: A4; margin: 20mm 18mm 20mm 18mm; @top-center { content: "DevLink③ FastExcel 并发导出"; font-size: 9pt; color: #666; } @bottom-center { co">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2026-09-29T05:59:03.210Z">
<meta property="article:modified_time" content="2026-09-29T05:59:03.210Z">
<meta property="article:author" content="Cassiur">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary_large_image">
<title>page.title - WhyAlwaysMe 的树洞</title>
<link rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />
<!-- 主题依赖的图标库,不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->
<link rel="stylesheet" href="//at.alicdn.com/t/c/font_1749284_5i9bdhy70f8.css">
<link rel="stylesheet" href="//at.alicdn.com/t/c/font_1736178_k526ubmyhba.css">
<link rel="stylesheet" href="/css/main.css" />
<link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
<link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
<script id="fluid-configs">
var Fluid = window.Fluid || {};
Fluid.ctx = Object.assign({}, Fluid.ctx)
var CONFIG = {"hostname":"whyalwaysme.lol","root":"/","version":"1.9.8","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0,"heading_selector":"h1,h2,h3,h4,h5,h6","collapse_depth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false},"umami":{"src":null,"website_id":null,"domains":null,"start_time":"2024-01-01T00:00:00.000Z","token":null,"api_server":null}},"search_path":"/local-search.xml","include_content_in_search":true};
if (CONFIG.web_analytics.follow_dnt) {
var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
}
</script>
<script src="/js/utils.js" ></script>
<script src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 8.1.1"></head>
<body>
<header>
<div class="header-inner" style="height: 60vh;">
<nav id="navbar" class="navbar fixed-top navbar-expand-lg navbar-dark scrolling-navbar">
<div class="container">
<a class="navbar-brand" href="/">
<strong>WhyAlwaysMe 的树洞</strong>
</a>
<button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<div class="animated-icon"><span></span><span></span><span></span></div>
</button>
<!-- Collapsible content -->
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto text-center">
<li class="nav-item">
<a class="nav-link" href="/" target="_self">
<i class="iconfont icon-home-fill"></i>
<span>首页</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/projects/" target="_self">
<i class="iconfont icon-code"></i>
<span>项目</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/archives/" target="_self">
<i class="iconfont icon-archive-fill"></i>
<span>归档</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/categories/" target="_self">
<i class="iconfont icon-category-fill"></i>
<span>分类</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/tags/" target="_self">
<i class="iconfont icon-tags-fill"></i>
<span>标签</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/about/" target="_self">
<i class="iconfont icon-user-fill"></i>
<span>关于</span>
</a>
</li>
<li class="nav-item" id="search-btn">
<a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
<i class="iconfont icon-search"></i>
</a>
</li>
<li class="nav-item" id="color-toggle-btn">
<a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
<i class="iconfont icon-dark" id="color-toggle-icon"></i>
</a>
</li>
</ul>
</div>
</div>
</nav>
<div id="banner" class="banner" parallax=true
style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
<div class="full-bg-img">
<div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
<div class="banner-text text-center fade-in-up">
<div class="h2">
<span id="subtitle" data-typed-text="page.title"></span>
</div>
</div>
</div>
</div>
</div>
</div>
</header>
<main>
<div class="container nopadding-x-md">
<div id="board"
>
<div class="container">
<div class="row">
<div class="col-12 col-md-10 m-auto">
<article class="page-content">
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DevLink③:FastExcel 并发导出 + 线程池调优(完整版)</title>
<style>
@page { size: A4; margin: 20mm 18mm 20mm 18mm;
@top-center { content: "DevLink③ FastExcel 并发导出"; font-size: 9pt; color: #666; }
@bottom-center { content: "第 " counter(page) " 页"; font-size: 9pt; color: #666; }
}
* { box-sizing: border-box; }
body {
font-family: "Microsoft YaHei", "Noto Sans CJK SC", "PingFang SC", sans-serif;
font-size: 11pt; line-height: 1.85; color: #1a1a2e;
max-width: 820px; margin: 0 auto; padding: 24px 28px; background: #fafbfc;
}
h1 { font-size: 22pt; color: #0d47a1; border-bottom: 3px solid #1565c0;
padding-bottom: 10px; margin-top: 48px; page-break-before: always; letter-spacing: 1px; }
h1:first-of-type { page-break-before: avoid; }
h2 { font-size: 15pt; color: #c62828; margin-top: 32px;
border-left: 5px solid #ef5350; padding-left: 12px;
background: linear-gradient(90deg, #fce4ec 0%, transparent 100%);
padding-top: 6px; padding-bottom: 6px; }
h3 { font-size: 12.5pt; color: #1b5e20; margin-top: 22px; font-weight: 600; }
h4 { font-size: 11pt; color: #e65100; margin-top: 16px; font-weight: 600; }
p { margin: 8px 0; text-align: justify; }
code { background: #e3f2fd; color: #0d47a1; padding: 2px 6px; border-radius: 4px;
font-family: "Consolas", "Courier New", monospace; font-size: 10pt; font-weight: 500; }
pre { background: #eceff1; border-left: 4px solid #1565c0; padding: 14px 18px;
font-size: 9.5pt; line-height: 1.6; overflow-x: auto; white-space: pre-wrap;
word-wrap: break-word; font-family: "Consolas", "Courier New", monospace;
margin: 12px 0; border-radius: 0 6px 6px 0; color: #263238; }
pre.block { background: #1a1a2e; color: #e0e0e0; border-left-color: #7c4dff; font-size: 9pt; }
pre.block code { background: none; color: inherit; padding: 0; }
table { width: 100%; border-collapse: collapse; margin: 14px 0; font-size: 10pt;
box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
th { background: #0d47a1; color: white; padding: 9px 12px; text-align: center; font-weight: 600; }
td { border: 1px solid #cfd8dc; padding: 7px 12px; text-align: center; }
tr:nth-child(even) { background: #e8eaf6; }
tr:hover { background: #c5cae9; }
.cover { text-align: center; padding: 60px 0 80px; page-break-after: always;
background: linear-gradient(135deg, #e8eaf6 0%, #fff 50%, #fce4ec 100%);
border-radius: 12px; margin-bottom: 20px; }
.cover h1 { font-size: 28pt; color: #0d47a1; border: none; page-break-before: avoid;
background: none; padding-bottom: 0; }
.cover .subtitle { font-size: 16pt; color: #555; margin: 24px 0 12px; font-weight: 400; }
.cover .info { font-size: 11pt; color: #777; margin: 10px 0; }
.tip { background: #e8f5e9; border-left: 5px solid #2e7d32; padding: 10px 16px;
margin: 12px 0; font-size: 10pt; border-radius: 0 6px 6px 0; }
.warn { background: #fff3e0; border-left: 5px solid #e65100; padding: 10px 16px;
margin: 12px 0; font-size: 10pt; border-radius: 0 6px 6px 0; }
.danger { background: #ffebee; border-left: 5px solid #f44336; padding: 10px 16px;
margin: 12px 0; font-size: 10pt; border-radius: 0 6px 6px 0; }
.highlight { background: #fffde7; border-left: 5px solid #f9a825; padding: 10px 16px;
margin: 12px 0; font-size: 10pt; border-radius: 0 6px 6px 0; }
.visual { background: #e3f2fd; border-radius: 8px; padding: 12px 16px;
margin: 10px 0; font-size: 10pt; line-height: 1.6; white-space: pre-wrap; }
.step { margin: 8px 0; padding: 8px 12px; background: #e8eaf6; border-radius: 6px; font-size: 10pt; }
.step-num { display: inline-block; background: #0d47a1; color: white;
border-radius: 50%; width: 22px; height: 22px;
text-align: center; line-height: 22px; margin-right: 8px; font-size: 9pt; }
.q { background: #e3f2fd; padding: 10px 14px; border-radius: 8px;
margin: 10px 0; border-left: 3px solid #1565c0; }
.q strong { color: #0d47a1; }
.ans { padding: 8px 14px; font-size: 10pt; color: #333; line-height: 1.7; }
.b { font-weight: bold; color: #0d47a1; }
.module-tag { display: inline-block; background: #0d47a1; color: white;
font-size: 9pt; padding: 2px 10px; border-radius: 12px;
margin-right: 6px; font-weight: 500; }
.compare-table td { vertical-align: top; text-align: left; padding: 8px 12px; }
ul { padding-left: 24px; }
li { margin: 4px 0; }
.end-page { text-align: center; padding: 120px 0; font-size: 16pt; color: #0d47a1;
page-break-before: always; }
.arch-box { background: #f5f5f5; border: 1px solid #ddd; border-radius: 8px;
padding: 16px; margin: 12px 0; font-size: 9.5pt; line-height: 1.7;
font-family: "Consolas", monospace; white-space: pre-wrap; }
@media print { body { font-size: 10.5pt; background: white; }
pre { font-size: 8.5pt; } .cover { page-break-after: always; background: white; }
table { box-shadow: none; } }
</style>
</head>
<body>
<!-- ====== 封面 ====== -->
<div class="cover">
<h1>DevLink ③<br>FastExcel 并发导出<br>+ 线程池调优</h1>
<p class="subtitle">暑期实习面试准备手册(完整版)</p>
<p class="info">技术栈:Spring Boot + FastExcel + ThreadPoolExecutor + CountDownLatch + ArrayBlockingQueue</p>
<p class="info">聚焦:并发导出 · 背压策略 · 线程安全 · OOM 防护 · 性能优化</p>
<p class="info">2026年6月 | 参考源码:paicoding-main 项目</p>
</div>
<!-- ====== 第一章:为什么要并发导出 ====== -->
<h1><span class="module-tag">模块一</span> 为什么要并发导出?</h1>
<h2>1.1 场景:导出 100 万条数据到 Excel</h2>
<div class="warn">证据更新(2026-09-29):以下展示的是分片查询与串行写出的设计机制。仓库没有连接真实数据库、走生产导出路径的可复现百万行端到端基准,因此不报告耗时或提升倍数。</div>
<div class="visual">❌ <b>不用并发(慢在哪里)?</b>
① 分页查询 DB;各页查询依次完成
② 主线程写 Excel
总耗时由数据库、数据量、网络与写出环境共同决定
✅ <b>用并发(快在哪里)?</b>
① 拆成多个分片,线程池并发查 DB
② 等所有分片完成并按顺序汇总
③ 由单线程 FastExcel 写出
是否缩短端到端时间,需要同环境基准验证</div>
<div class="tip">✅ <b>核心思想:</b>查 DB 是瓶颈(IO 密集),用多线程并发查;
写 Excel 不是瓶颈(CPU + 磁盘 IO),单线程写就够,而且必须单线程(线程安全)。</div>
<h2>1.2 为什么写 Excel 要单线程?</h2>
<div class="q"><strong>Q:FastExcel 的写操作为什么不能并发?</strong></div>
<div class="ans">
<p>FastExcel(和 EasyExcel)的 <code>ExcelWriter</code> <b>不是线程安全</b>的:</p>
<ul>
<li>内部有 <code>currentSheet</code>(当前 Sheet)、<code>rowCount</code>(当前行号)等共享状态</li>
<li>多线程同时调 <code>write()</code> → 行号错乱、Sheet 错乱、文件损坏</li>
<li><b>必须单线程写</b>,或者每个线程写独立文件最后合并(更复杂,不值得)</li>
</ul>
<p class="b">项目的做法:多线程只负责"查数据",全部查完后由主线程"写 Excel"。</p>
</div>
<h2>1.3 如何验证性能</h2>
<p>在相同数据库、数据集、导出路径和机器环境下,分别多次运行串行与并发方案,记录查询、汇总、写出和总耗时的分布,并观察内存与数据库负载。当前没有这样的可复核结果。</p>
<div class="warn">⚠️ <b>注意:</b>并发查 DB 只能加速"查数据"阶段。
如果数据量太大(1000 万条),即使并发查,<b>内存存不下</b>也会 OOM。
这种情况要用"生产者-消费者模式"(后面详细讲)。</div>
<!-- ====== 第二章:线程池核心概念 ====== -->
<h1><span class="module-tag">模块二</span> 线程池核心概念(面试必背)</h1>
<h2>2.1 为什么要用线程池?(不是直接 new Thread)</h2>
<div class="visual"><b>不用线程池(坏做法):</b>
for (int i = 0; i < 100; i++) {
new Thread(() -> queryData()).start(); // 每次都创建新线程
}
→ 创建 100 个线程,每个线程占 1MB 栈内存 = <b>100MB 内存浪费</b>
→ 线程创建/销毁开销大(每次 ~1ms)
→ 系统可能撑不住(Linux 默认线程数限制 ~1000)
<b>用线程池(好做法):</b>
线程池里只有 <b>8 个核心线程</b>(和 CPU 核心数对齐)
→ 100 个任务来了,<b>8 个线程轮流处理</b>,不创建新线程
→ 节省内存(8 个线程 × 1MB = 8MB)
→ 节省时间(不用每次创建/销毁线程)
</div>
<h2>2.2 线程池的 7 个参数(面试必背!)</h2>
<pre class="block">// Java 线程池的核心构造器(必须会写!)
new ThreadPoolExecutor(
int corePoolSize, // ① 核心线程数(长期驻留的线程数)
int maximumPoolSize, // ② 最大线程数(忙时最多能开多少线程)
long keepAliveTime, // ③ 空闲线程存活时间
TimeUnit unit, // ④ 时间单位
BlockingQueue<Runnable> workQueue, // ⑤ 工作队列(存等待执行的任务)
ThreadFactory threadFactory, // ⑥ 线程工厂(给线程起名字)
RejectedExecutionHandler handler // ⑦ 拒绝策略(队列满了怎么办)
)</pre>
<table class="compare-table">
<tr><th>参数</th><th>项目中设置</th><th>说明</th><th>面试追问</th></tr>
<tr><td>corePoolSize</td><td>8</td><td>核心线程数(长期驻留)</td><td>为什么是 8?(CPU 核心数)</td></tr>
<tr><td>maximumPoolSize</td><td>16</td><td>最大线程数</td><td>为什么是 16 不是 80?</td></tr>
<tr><td>keepAliveTime</td><td>60 秒</td><td>非核心线程空闲 60 秒后回收</td><td>为什么是 60 秒?</td></tr>
<tr><td>workQueue</td><td>ArrayBlockingQueue(11)</td><td>有界队列(最多 11 个任务在排队)</td><td>为什么不用 LinkedBlockingQueue?</td></tr>
<tr><td>handler</td><td>CallerRunsPolicy</td><td>调用者线程自己跑任务(背压!)</td><td>为什么不用 AbortPolicy?</td></tr>
</table>
<h2>2.3 线程池执行流程(面试必画!)</h2>
<div class="visual"><b>任务提交的完整流程:</b>
① 任务来了 → 如果当前线程数 < corePoolSize
→ <b>创建新线程</b>(核心线程)来执行这个任务
② 任务继续来 → 核心线程都在忙
→ 任务放进 <b>工作队列</b>(workQueue)
③ 任务继续来 → 工作队列满了
→ 如果当前线程数 < maximumPoolSize
→ <b>创建新线程</b>(非核心线程)来执行任务
④ 任务继续来 → 线程数已达 maximumPoolSize,队列也满了
→ 触发 <b>拒绝策略</b>(handler)
<b>关键:项目里 maximumPoolSize=16,但队列只有 11 个位置</b>
→ 8 个核心线程在忙 + 11 个任务在排队 = 19 个任务
→ 第 20 个任务来时,才会创建非核心线程(到第 16 个)
→ 但实际上:队列满了(11 个)就会触发 <b>CallerRunsPolicy</b>
→ <b>不会创建非核心线程!</b>(因为 CallerRunsPolicy 会阻塞提交)
</div>
<h2>2.4 为什么 corePoolSize = 8?(CPU 核心数)</h2>
<div class="q"><strong>Q:导出是 IO 密集型,为什么 corePoolSize 不是 CPU×2?</strong></div>
<div class="ans">
<p><b>答:</b>这取决于"查 DB"是 IO 密集还是 CPU 密集。</p>
<ul>
<li><b>纯 IO 密集</b>(查 DB、调 RPC):线程大部分时间在<b>等</b>(等 DB 返回),CPU 是空闲的
→ 应该设 <code>CPU核心数 × 2</code>(让更多线程同时等,提高吞吐量)</li>
<li><b>IO + 计算混合</b>(查 DB + 数据转换):线程有一部分时间在用 CPU
→ 应该设 <code>CPU核心数 + 1</code> 或 <code>CPU核心数 × 1.5</code></li>
<li><b>项目的情况</b>:查 DB 是 IO 密集,但每个任务查完数据后还要做数据转换(DTO 转换)→ IO + 计算混合
→ 设 8(CPU 核心数)是合理的,如果想更激进可以设 12~16</li>
</ul>
<p class="b">面试加分:"我们的场景是 IO + 计算混合,所以设了 CPU 核心数。如果是纯 IO 场景(比如只是转发请求),会设 CPU×2。"</p>
</div>
<!-- ====== 第三章:源码深挖 ====== -->
<h1><span class="module-tag">模块三</span> 源码深挖:完整流程</h1>
<h2>3.1 第 1 步:算分片数</h2>
<pre class="block">// 文件位置:paicoding-service/.../service/impl/StatisticsSettingServiceImpl.java
// 方法:downloadRequestCount2ExcelConcurrent()
long total = requestCountService.count(); // 先查总记录数
int shardCount = (int) Math.ceil((double) total / BATCH_SIZE);
// 例子:total = 100万,BATCH_SIZE = 10万 → shardCount = 10 个分片
// 为什么要分片?
// → 串行分页查询可能受 DB 往返耗时影响
// → 分片可并发查询;具体收益以真实数据库基准为准</pre>
<h2>3.2 第 2 步:创建自定义线程池(关键配置!)</h2>
<pre class="block">// 文件位置:同上(第 60-66 行左右)
ThreadPoolExecutor executor = new ThreadPoolExecutor(
CORE_POOL, // 8 → 核心线程数(和 CPU 核心数对齐)
MAX_POOL, // 16 → 最大线程数
60L, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(shardCount + 1), // ★ 有界队列!(关键!)
r -> new Thread(r, "excel-export-" + r.hashCode()),
new ThreadPoolExecutor.CallerRunsPolicy() // ★ 背压策略!(关键!)
);
// ★ 为什么用 ArrayBlockingQueue(有界队列)?
// → 防止任务无限堆积,导致 OOM
// → 队列大小 = shardCount + 1(刚好够用,不浪费内存)
// ★ 为什么用 CallerRunsPolicy(调用者运行策略)?
// → 队列满了,提交任务的线程(主线程)自己来跑这个任务
// → 主线程被占用 → 不能继续提交新任务 → 天然背压(限速)!</pre>
<h2>3.3 为什么用 ArrayBlockingQueue(有界队列)?</h2>
<table>
<tr><th>队列类型</th><th>是否有界</th><th>可能的问题</th><th>项目选择</th></tr>
<tr><td><code>LinkedBlockingQueue</code>(无界)</td><td>❌ 无界(默认 Integer.MAX_VALUE)</td><td>任务无限堆积 → <b>OOM</b></td><td>❌ 不用</td></tr>
<tr><td><code>ArrayBlockingQueue</code>(有界)</td><td>✅ 有界(构造时指定大小)</td><td>队列满了 → 触发 <b>拒绝策略</b></td><td>✅ 项目用的这个</td></tr>
<tr><td><code>SynchronousQueue</code>(同步)</td><td>✅ 容量为 0(不存任务)</td><td>直接交付给线程,适合<code>maximumPoolSize</code> 很大的场景</td><td>❌ 不适合(分片数固定)</td></tr>
</table>
<div class="danger">⚠️ <b>OOM 风险:</b>如果 100 万数据拆成 1000 个分片,
<code>shardCount + 1 = 1001</code>,任务会全部放进队列(1001 个),
每个任务查 1000 条数据(存到内存),可能撑爆内存。<br>
<b>优化方案:</b>限制最大分片数(比如最多 20 个分片),超过的部分串行处理。
或者用"生产者-消费者模式"(不存全量数据到内存)。</div>
<h2>3.4 CallerRunsPolicy(背压策略)是什么?</h2>
<div class="visual"><b>场景:</b>队列满了(10 个任务在排队),再来新任务怎么办?
<b>① AbortPolicy(默认):</b>
抛 <code>RejectedExecutionException</code> → 任务丢失
(不适合导出场景:用户点击"导出",结果任务被丢弃,用户不知道为什么)
<b>② DiscardPolicy(丢弃):</b>
直接丢弃新任务 → 任务丢失(和上面一样不适合)
<b>③ CallerRunsPolicy(调用者运行,项目用的):</b>
→ 提交任务的线程(主线程)<b>自己来跑这个任务</b>
→ 主线程被占用 → <b>不能继续提交新任务</b> → 天然背压(限速)!
→ 不会丢任务,也不会 OOM(因为提交速度自动慢下来)
<b>④ DiscardOldestPolicy(丢弃最老的):</b>
丢弃队列里最老的任务,放入新任务
(适合"最新数据最重要"的场景,不适合导出)
</div>
<div class="tip">✅ <b>CallerRunsPolicy 的妙处:</b>不丢任务 + 自动限速(背压)。
主线程被占用时,提交速度自然慢下来,不会压垮系统。<br>
<b>生活比喻:</b>餐厅厨房满了(队列满),服务员(主线程)自己去帮忙做菜(执行任务),
就不能继续接新订单了 → 顾客(任务提交方)看到服务员在忙,就会等一会再点餐 → 天然限速!
</div>
<h2>3.5 第 3 步:提交分片任务 + CountDownLatch 等待</h2>
<pre class="block">// 文件位置:同上(第 68-85 行左右)
CountDownLatch latch = new CountDownLatch(shardCount);
List<List<RequestCountDO>> result = new ArrayList<>();
for (int i = 0; i < shardCount; i++) {
final int shardIndex = i;
executor.submit(() -> {
try {
// 每个线程查自己的分片(OFFSET = shardIndex * BATCH_SIZE)
List<RequestCountDO> shardData =
requestCountService.queryByPage(shardIndex * BATCH_SIZE, BATCH_SIZE);
// ★ 需要同步!因为 result 是共享的 ArrayList
synchronized (result) {
result.addAll(shardData); // 把分片数据合并到总结果
}
} finally {
latch.countDown(); // 完成一个分片,计数器 -1
}
});
}
latch.await(); // ★ 主线程等待所有分片完成(计数器到 0)
// 到这里,result 已经包含所有分片的数据 → 可以写 Excel 了</pre>
<h2>3.6 第 4 步:单线程写 Excel</h2>
<pre class="block">// 所有分片数据已就绪,主线程写 Excel(单线程,线程安全!)
FastExcel.write(response.getOutputStream(), RequestCountDO.class)
.sheet("request_count")
.doWrite(result); // ★ 单线程写,线程安全
executor.shutdown(); // 关闭线程池(不再接受新任务)
executor.awaitTermination(30, TimeUnit.SECONDS); // 等待所有任务完成</pre>
<div class="warn">⚠️ <b>注意:</b><code>result</code> 是 <code>ArrayList</code>(不是线程安全的!),
所以合并结果时要加 <code>synchronized (result)</code>。<br>
<b>更好的方案:</b>用 <code>Future</code> 代替 <code>CountDownLatch</code>(后面讲)。
</div>
<!-- ====== 第四章:CountDownLatch 原理 ====== -->
<h1><span class="module-tag">模块四</span> CountDownLatch 原理(面试必考)</h1>
<h2>4.1 生活比喻</h2>
<div class="visual"><b>CountDownLatch = 倒计时门栓</b>
比赛开始:10 个运动员准备 → 裁判喊"开始" → 所有人同时跑
→ <code>latch.await()</code> = 主线程在门口等
→ <code>latch.countDown()</code> = 每个运动员到达终点,计数器 -1
→ 计数器到 0 → 门栓打开 → 主线程继续(开始汇总成绩)
<b>关键:</b>CountDownLatch <b>只能用一次</b>(计数器到 0 后就废了)。
如果要再次使用,要新建一个 CountDownLatch。
</div>
<h2>4.2 源码核心(面试追问)</h2>
<pre class="block">// CountDownLatch 的核心:AQS(AbstractQueuedSynchronizer)
public class CountDownLatch {
private static final class Sync extends AbstractQueuedSynchronizer {
Sync(int count) {
setState(count); // AQS 的 state 字段 = 计数器初始值
}
// await():state != 0 时,线程进入等待队列
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1; // state=0 → 获取成功(不阻塞)
}
// countDown():state - 1,如果 state=0 就唤醒所有等待线程
protected boolean tryReleaseShared(int releases) {
for (;;) {
int c = getState();
if (c == 0) return false; // 已经到 0 了,不用再释放
int nextc = c - 1;
if (compareAndSetState(c, nextc)) // CAS 原子操作
return nextc == 0; // 如果到 0 了,唤醒所有等待线程
}
}
}
// 调用方代码
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1); // 调用 AQS 的模板方法
}
public void countDown() {
sync.releaseShared(1); // 调用 AQS 的模板方法
}
}</pre>
<div class="tip">✅ <b>面试加分:</b>说出 CountDownLatch 是基于 <b>AQS(AbstractQueuedSynchronizer)</b> 实现的,
内部用 <code>state</code> 字段表示计数器,用 <b>CAS(Compare-And-Swap)</b> 保证原子性。<br>
这能体现你不仅"会用",还知道"为什么能用"。
</div>
<h2>4.3 vs CyclicBarrier vs Semaphore(面试必背对比!)</h2>
<table>
<tr><th>工具</th><th>作用</th><th>是否可复用</th><th>典型场景</th><th>项目用的</th></tr>
<tr><td><code>CountDownLatch</code></td><td>等待 N 个线程完成</td><td>❌ 一次性</td><td>等待所有分片查完</td><td>✅ 用的是这个</td></tr>
<tr><td><code>CyclicBarrier</code></td><td>N 个线程互相等待</td><td>✅ 可复用</td><td>分片之间需要交换数据时用</td><td>❌ 没用</td></tr>
<tr><td><code>Semaphore</code></td><td>限制同时访问的线程数</td><td>✅ 可复用</td><td>限制 DB 连接数时用</td><td>❌ 没用</td></tr>
</table>
<div class="q"><strong>Q:为什么项目用 CountDownLatch 而不用 CyclicBarrier?</strong></div>
<div class="ans">
<p><b>答:</b>因为项目中"分片之间不需要交换数据"。</p>
<ul>
<li><code>CountDownLatch</code>:主线程等所有分片完成 → <b>汇总结果</b></li>
<li><code>CyclicBarrier</code>:分片之间要互相等待,到了屏障点交换数据 → <b>分片协作</b></li>
<li>项目里每个分片独立查自己的数据,不需要和其他分片交换 → 用 CountDownLatch 更简单</li>
</ul>
</div>
<!-- ====== 第五章:面试八股文 ====== -->
<h1><span class="module-tag">模块五</span> 面试八股文大全</h1>
<h2>5.1 线程池篇</h2>
<div class="q"><strong>Q1:线程池的 7 个参数,你项目里怎么设置的?为什么?</strong></div>
<div class="ans">
<pre class="block">ThreadPoolExecutor(
corePoolSize = 8, // CPU 核心数(IO + 计算混合场景)
maximumPoolSize = 16, // 最大线程数(实际上不会用到,因为队列满了就触发 CallerRunsPolicy)
keepAliveTime = 60, // 非核心线程空闲 60 秒后回收(节省资源)
unit = TimeUnit.SECONDS,
workQueue = new ArrayBlockingQueue<>(shardCount + 1), // 有界队列(防止 OOM)
threadFactory = r -> new Thread(r, "excel-export-" + r.hashCode()),
handler = new ThreadPoolExecutor.CallerRunsPolicy() // 背压策略(防止 OOM)
)</pre>
<p><b>为什么 corePoolSize = 8?</b> 导出是 IO + 计算混合场景,设 CPU 核心数。<br>
如果是纯 IO 场景(比如只是转发请求),会设 CPU×2。</p>
</div>
<div class="q"><strong>Q2:如果导出 1000 万数据,你的方案会出什么问题?怎么优化?</strong></div>
<div class="ans">
<ul>
<li><b>问题 1:</b><code>result</code> 列表存全部数据 → <b>OOM</b>(内存存不下 1000 万条)</li>
<li><b>问题 2:</b>分片数太多 → 任务太多 → 调度开销大</li>
<li><b>优化方案:</b>改用 <b>生产者-消费者模式</b>(见下题)</li>
</ul>
</div>
<div class="q"><strong>Q3:更好的方案 —— 生产者-消费者模式</strong></div>
<div class="ans">
<pre class="block">// 生产者:10 个线程查 DB,查到一批就放进队列
executor.submit(() -> {
while (hasMoreData()) {
List<RequestCountDO> batch = queryBatch(); // 查一批(比如 1000 条)
blockingQueue.put(batch); // 队列满了自动阻塞(背压!)
}
});
// 消费者:1 个线程从队列取数据,写 Excel(流式写)
while (true) {
List<RequestCountDO> batch = blockingQueue.poll(3, TimeUnit.SECONDS);
if (batch == null) break; // 所有生产者都完了
excelWriter.write(batch); // 流式写,不存全量数据
}</pre>
<p class="b">优点:不存全量数据到内存(用队列缓冲),支持任意大数据量导出。</p>
</div>
<h2>5.2 CountDownLatch 篇</h2>
<div class="q"><strong>Q4:CountDownLatch 和 Future 的区别?项目中用哪个更好?</strong></div>
<div class="ans">
<table>
<tr><th>工具</th><th>能否获取返回值</th><th>能否取消任务</th><th>项目适用性</th></tr>
<tr><td><code>CountDownLatch</code></td><td>❌ 不能(只能等完成)</td><td>❌ 不能</td><td>✅ 可以用,但要自己合并结果(加锁)</td></tr>
<tr><td><code>Future</code></td><td>✅ 能(<code>future.get()</code>)</td><td>✅ 能(<code>future.cancel()</code>)</td><td>✅ <b>更好!</b>无需加锁,代码更简洁</td></tr>
</table>
<p><b>用 Future 优化项目代码:</b></p>
<pre class="block">List<Future<List<RequestCountDO>>> futures = new ArrayList<>();
for (int i = 0; i < shardCount; i++) {
futures.add(executor.submit(() -> queryShard(i))); // 返回 Future
}
// 主线程收结果(无锁!)
for (Future<?> f : futures) {
result.addAll(f.get()); // get() 自动等待,且无需 synchronized
}</pre>
</div>
<h2>5.3 FastExcel 篇</h2>
<div class="q"><strong>Q5:FastExcel 和 EasyExcel 的关系?</strong></div>
<div class="ans">
<ul>
<li>当前仓库在 <code>pom.xml</code> 中使用 <code>cn.idev:fastexcel:1.0.0</code></li>
<li>项目未验证与 EasyExcel 的完整 API 兼容性,迁移前需要逐项测试</li>
<li>核心优化:<b>SAX 模式解析</b>(逐行读,不加载全量到内存)</li>
<li>支持 <b>流式写</b>(<code>excelWriter.write(batch)</code> 可以多次调用,每次写一批)</li>
</ul>
</div>
<div class="q"><strong>Q6:EasyExcel/FastExcel 的 SAX 模式是什么?</strong></div>
<div class="ans">
<p><b>传统 DOM 模式(不好):</b></p>
<ul>
<li>把整个 Excel 文件加载到内存 → 大文件会 OOM</li>
<li>适合小文件(几 MB)</li>
</ul>
<p><b>SAX 模式(好!):</b></p>
<ul>
<li><b>逐行解析</b>,读到一行就回调一行 → 不加载全量到内存</li>
<li>适合大文件(几百 MB)</li>
<li>FastExcel 读 Excel 默认用 SAX 模式(自动的,不用配置)</li>
</ul>
</div>
<!-- ====== 第六章:项目不足与优化方向 ====== -->
<h1><span class="module-tag">模块六</span> 项目不足与优化方向(面试加分必说)</h1>
<h2>6.1 项目存在的不足(诚实说出来,加分!)</h2>
<div class="danger"><strong>不足 1:</strong><code>synchronized (result)</code> 合并结果会成为瓶颈。<br>
<b>优化方案:</b>用 <code>Future</code> 代替 <code>CountDownLatch</code>,
每个分片返回自己的结果,主线程无锁合并(见 Q4)。
</div>
<div class="danger"><strong>不足 2:</strong>如果导出 1000 万数据,<code>result</code> 列表会 OOM。<br>
<b>优化方案:</b>改用"生产者-消费者模式",不存全量数据到内存(见 Q3)。
</div>
<div class="danger"><strong>不足 3:</strong>线程池没有复用,每次导出都创建新线程池。<br>
<b>优化方案:</b>把线程池定义为 Spring Bean(<code>@Bean</code>),所有导出任务复用同一个线程池。
</div>
<div class="danger"><strong>不足 4:</strong>没有做"导出进度"功能,用户不知道还要等多久。<br>
<b>优化方案:</b>用 Redis 存进度(<code>export:progress:{taskId}</code>),
前端通过 WebSocket 轮询或推送进度。
</div>
<h2>6.2 架构优化方向</h2>
<div class="tip"><strong>优化 1:</strong>支持"异步导出"(提交导出任务后,返回 taskId,
用户可以去干别的,导出完了收到通知再来下载)。适合大数据量导出。</div>
<div class="tip"><strong>优化 2:</strong>限制同时导出的任务数(比如最多 3 个同时在导),
防止多个用户同时导出把系统资源耗尽。用 <code>Semaphore</code> 实现。</div>
<div class="tip"><strong>优化 3:</strong>导出完成后自动上传到 OSS(对象存储),
返回下载链接。适合分布式部署(多个实例共享文件)。</div>
<!-- ====== 结尾 ====== -->
<div class="end-page">
<p>🎯 祝你面试顺利,拿到心仪的 Offer!</p>
<p style="font-size: 11pt; color: #777; margin-top: 20px;">
上一页:DevLink ② 策略工厂模式 + WebSocket 流式推送<br>
返回总览:DevLink 项目深度解析
</p>
</div>
</body>
</html>
</article>
</div>
</div>
</div>
</div>
</div>
<a id="scroll-top-button" aria-label="TOP" href="#" role="button">
<i class="iconfont icon-arrowup" aria-hidden="true"></i>
</a>
<div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
<div class="modal-content">
<div class="modal-header text-center">
<h4 class="modal-title w-100 font-weight-bold">搜索</h4>
<button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body mx-3">
<div class="md-form mb-5">
<input type="text" id="local-search-input" class="form-control validate">
<label data-error="x" data-success="v" for="local-search-input">关键词</label>
</div>
<div class="list-group" id="local-search-result"></div>
</div>
</div>
</div>
</div>
</main>
<footer>
<div class="footer-inner">
<div class="footer-content">
<span>Made with Hexo & Fluid</span><br><span>© 2025 Cassiur</span>
</div>
</div>
</footer>
<!-- Scripts -->
<script src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
<link rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />
<script>
NProgress.configure({"showSpinner":false,"trickleSpeed":100})
NProgress.start()
window.addEventListener('load', function() {
NProgress.done();
})
</script>
<script src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script src="/js/events.js" ></script>
<script src="/js/plugins.js" ></script>
<script src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
<script>
(function (window, document) {
var typing = Fluid.plugins.typing;
var subtitle = document.getElementById('subtitle');
if (!subtitle || !typing) {
return;
}
var text = subtitle.getAttribute('data-typed-text');
typing(text);
})(window, document);
</script>
<script src="/js/img-lazyload.js" ></script>
<script src="/js/local-search.js" ></script>
<script src="/js/deepseek-widget.js"></script>
<!-- 主题的启动项,将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script src="/js/boot.js" ></script>
<noscript>
<div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
</noscript>
</body>
</html>