/
java.html
697 lines (504 loc) · 24.7 KB
/
java.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
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>
Java - IMLC.ME
</title>
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="atom.xml" rel="alternate" title="IMLC.ME" type="application/atom+xml">
<link href="asset/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">
<link href="asset/stylesheets/font-awesome.min.css" media="screen, projection" rel="stylesheet" type="text/css">
<script src="asset/javascripts/jquery.min.js"></script>
<script src="asset/highlightjs/highlight.pack.js"></script>
<link href="asset/highlightjs/styles/solarized_dark.css" media="screen, projection" rel="stylesheet" type="text/css">
<script>hljs.initHighlightingOnLoad();</script>
<!--[if lt IE 9]><script src="asset/javascripts/html5.js"></script><![endif]-->
<!-- <link href='http://fonts.googleapis.com/css?family=Nunito:400,300,700' rel='stylesheet' type='text/css'> -->
<style type="text/css">
/* latin */
@font-face {
font-family: 'Nunito';
font-style: normal;
font-weight: 300;
src: local('Nunito-Light'), url(asset/font/1TiHc9yag0wq3lDO9cw0voX0hVgzZQUfRDuZrPvH3D8.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* latin */
@font-face {
font-family: 'Nunito';
font-style: normal;
font-weight: 400;
src: local('Nunito-Regular'), url(asset/font/6TbRXKWJjpj6V2v_WyRbMX-_kf6ByYO6CLYdB4HQE-Y.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* latin */
@font-face {
font-family: 'Nunito';
font-style: normal;
font-weight: 700;
src: local('Nunito-Bold'), url(asset/font/TttUCfJ272GBgSKaOaD7KoX0hVgzZQUfRDuZrPvH3D8.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
</style>
<style type="text/css">
.container .left-col{ opacity: 1;}
#pagenavi a{ font-size: 1.3em;}
#pagenavi .next:before{ top: 3px;}
#pagenavi .prev:before{ top: 3px;}
#projects-nav {margin-left: 10px;}
#projects-nav li {
list-style: none;
}
.container .mid-col .mid-col-container #content .archives .title{ font-size: 1.5em;}
.container .mid-col .mid-col-container #content article{ padding: 15px 0px;}
#header .subtitle {
line-height: 1.2em;
padding-top: 8px;
}
article pre{ background: none; border: none; padding: 0;}
article .entry-content{text-align: left;}
.share-comment{ padding: 25px 0px; clear: both;}
hr{ margin: 20px 0px;border: 0; border-top:solid 1px #ddd;}
</style>
</head>
<body>
<div class="container">
<div class="left-col">
<div class="intrude-less">
<header id="header" class="inner">
<div class="profilepic">
<img src="/asset/icon.jpg" style="width:160px;">
</div>
<h1><a href="index.html">IMLC.ME</a></h1>
<p class="subtitle"></p>
<nav id="main-nav">
<ul class="main">
<li id=""><a target="self" href="index.html">Home</a></li>
<li id=""><a target="_self" href="archives.html">Archives</a></li>
</ul>
</nav>
<nav>
My Projects
<ul id="projects-nav">
</ul>
</nav>
<nav id="sub-nav">
<div class="social">
<a target="_blank" class="github" target="_blank" href="https://github.com/lawrenceching" title="GitHub">GitHub</a>
<a class="rss" href="atom.xml" title="RSS">RSS</a>
</div>
</nav>
</header>
</div>
</div>
<div class="mid-col">
<div class="mid-col-container">
<div id="content" class="inner">
<div itemscope itemtype="http://schema.org/Blog">
<article class="post" itemprop="blogPost" itemscope itemtype="http://schema.org/BlogPosting">
<div class="meta">
<div class="date">
<time datetime="2018-04-06T23:25:13+08:00" itemprop="datePublished">2018/4/6</time>
</div>
<div class="tags">posted in
<a class='category' href='java.html'>Java</a>
</div>
</div>
<h1 class="title" itemprop="name"><a href="15230283138027.html" itemprop="url">
Hello Spring Actuator</a></h1>
<div class="entry-content" itemprop="articleBody">
<h2 id="toc_0">Start Up The Service</h2>
<h2 id="toc_1">Customize Health Check</h2>
</div>
</article>
<article class="post" itemprop="blogPost" itemscope itemtype="http://schema.org/BlogPosting">
<div class="meta">
<div class="date">
<time datetime="2018-03-21T23:24:15+08:00" itemprop="datePublished">2018/3/21</time>
</div>
<div class="tags">posted in
<a class='category' href='java.html'>Java</a>
</div>
</div>
<h1 class="title" itemprop="name"><a href="remote-debugging-for-java-application.html" itemprop="url">
Remote Debugging for Java Application</a></h1>
<div class="entry-content" itemprop="articleBody">
<p>It's an important feature that JVM provided and I'm so surprised that I used it at the first time today.</p>
<h2 id="toc_0">How to enable remote debugging</h2>
<p>To enable it, you will just need to add below JVM arguments in command line:</p>
<pre><code>-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
</code></pre>
<p>Then you can use your debugger to attach to remote JVM.</p>
<p><code>suspend</code> is quite useful argument here. If <code>suspend</code> is <code>y</code>, JVM will suspend before main class is loaded until debugger attach to it. <code>n</code> otherwise. </p>
<p>So set <code>suspend</code> to <code>y</code> if you need to debug application initialization phase.</p>
<p><a href="https://docs.oracle.com/javase/7/docs/technotes/guides/jpda/conninv.html">Check Official Document for detailed introduction</a></p>
<h2 id="toc_1">Remote Debugging in IntelliJ IDEA</h2>
<p>I believe all IDEs have that function to debug Java application remotely. I use IntelliJ here for demonstration.</p>
<p><img src="media/15216458555103/Remote%20Debug%20Configuration%20in%20IntelliJ.png" alt="Remote Debug Configuration in IntelliJ"/><br/>
Add a new configuration under Remote category, you will see IntelliJ provides command line arguments for you. That's exactly what I show in previous section.</p>
<p>Change the host to your server's url, and launch your application with remote debug arguments, then you can debug as what you did on debugging local application.</p>
<h1 id="toc_2">DO NOT REMOTE DEBUG YOUR PRODUCTION APPLICATION</h1>
</div>
</article>
<article class="post" itemprop="blogPost" itemscope itemtype="http://schema.org/BlogPosting">
<div class="meta">
<div class="date">
<time datetime="2017-09-25T22:03:13+08:00" itemprop="datePublished">2017/9/25</time>
</div>
<div class="tags">posted in
<a class='category' href='java.html'>Java</a>
</div>
</div>
<h1 class="title" itemprop="name"><a href="15063481937597.html" itemprop="url">
How to serve one jersey resource or jetty servlet for different path</a></h1>
<div class="entry-content" itemprop="articleBody">
<p>Today I'm trying to make an endpoint accessible in different paths. Such as I can go to <code>http://localhost/</code> and <code>http://localhost/hello</code> for a same hello message. </p>
<p>I do got some solutions.</p>
<p>I'm using Jersey over Jetty. But whether or not you're using Jetty servlet or writing Jersey Resource, I think you will get some ideas.</p>
<p>Ps: I copy the code from my GitLab Snippets and will keep it update. So If you find something wrong, pls comment in GitLab</p>
<h3 id="toc_0">Using the regular expression in Jersey Resource</h3>
<p><a href="https://gitlab.com/snippets/1676612">https://gitlab.com/snippets/1676612</a></p>
<pre><code class="language-java">package me.imlc.example.jetty.multiplehandler;
import com.sun.jersey.spi.container.servlet.ServletContainer;
import me.imlc.example.jetty.multplehandler.HelloResource;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Objects;
import static org.junit.Assert.assertEquals;
public class RegexpResourceTest {
private static Server server;
private static CloseableHttpClient client = HttpClients.createDefault();
@BeforeClass
public static void beforeAll() throws Exception {
ResourceConfig rc = new ResourceConfig(RegexpResource.class);
ServletHolder holder = new ServletHolder(new ServletContainer(rc));
server = new Server(8080);
ServletContextHandler contextHandler = new ServletContextHandler(server, "/*");
contextHandler.addServlet(holder, "/*");
server.start();
}
@Test
public void canAccessByRootPath() throws Exception {
HttpGet get = new HttpGet("http://localhost:8080/hello");
String content = EntityUtils.toString(client.execute(get).getEntity());
assertEquals(content, "Hello, Lynn.");
}
@Test
public void canAccessByServicePath() throws Exception {
HttpGet get = new HttpGet("http://localhost:8080/service/hello");
String content = EntityUtils.toString(client.execute(get).getEntity());
assertEquals(content, "Hello, Lynn.");
}
@AfterClass
public static void afterAll() throws Exception {
if(Objects.nonNull(server)) server.stop();
if(Objects.nonNull(client)) client.close();
}
@Path("/{a:(.*)|service}")
public static class RegexpResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello, Lynn.";
}
}
}
</code></pre>
<h3 id="toc_1">Specify multiple paths for one servlet</h3>
<p><a href="https://gitlab.com/snippets/1676613">https://gitlab.com/snippets/1676613</a></p>
<pre><code class="language-java">package me.imlc.example.jetty.multiplehandler;
import com.sun.jersey.spi.container.servlet.ServletContainer;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Objects;
import static org.junit.Assert.assertEquals;
public class MultipleServletTest {
private static Server server;
private static CloseableHttpClient client = HttpClients.createDefault();
@BeforeClass
public static void beforeAll() throws Exception {
ResourceConfig rc = new ResourceConfig(RegexpResourceTest.RegexpResource.class);
ServletHolder holder = new ServletHolder(new ServletContainer(rc));
server = new Server(8080);
ServletContextHandler contextHandler = new ServletContextHandler(server, "/*");
contextHandler.addServlet(holder, "/*");
contextHandler.addServlet(holder, "/service/*");
server.start();
}
@Test
public void canAccessByRootPath() throws Exception {
HttpGet get = new HttpGet("http://localhost:8080/hello");
String content = EntityUtils.toString(client.execute(get).getEntity());
assertEquals(content, "Hello, Lynn.");
}
@Test
public void canAccessByServicePath() throws Exception {
HttpGet get = new HttpGet("http://localhost:8080/service/hello");
String content = EntityUtils.toString(client.execute(get).getEntity());
assertEquals(content, "Hello, Lynn.");
}
@AfterClass
public static void afterAll() throws Exception {
if(Objects.nonNull(server)) server.stop();
if(Objects.nonNull(client)) client.close();
}
@Path("/hello")
public static class MultipleServletResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello, Lynn.";
}
}
}
</code></pre>
<h3 id="toc_2">Serve one servlet in different context handler</h3>
<p><a href="https://gitlab.com/snippets/1676615">https://gitlab.com/snippets/1676615</a></p>
<pre><code class="language-java">package me.imlc.example.jetty.multiplehandler;
import com.sun.jersey.spi.container.servlet.ServletContainer;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Objects;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import static org.junit.Assert.assertEquals;
public class MultipleContextHandlerTest {
private static Server server;
private static CloseableHttpClient client = HttpClients.createDefault();
@BeforeClass
public static void beforeAll() throws Exception {
ResourceConfig rc = new ResourceConfig(MultipleContextHandlerResource.class);
ServletHolder holder = new ServletHolder(new ServletContainer(rc));
server = new Server(8080);
ServletContextHandler rootContext = new ServletContextHandler(server, "/*");
rootContext.addServlet(holder, "/*");
ServletContextHandler serviceContext = new ServletContextHandler(server, "/service/*");
serviceContext.addServlet(holder, "/*");
ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection();
contextHandlerCollection.setHandlers(new Handler[]{
rootContext, serviceContext
});
server.setHandler(contextHandlerCollection);
server.start();
}
@Test
public void canAccessByRootPath() throws Exception {
HttpGet get = new HttpGet("http://localhost:8080/hello");
String content = EntityUtils.toString(client.execute(get).getEntity());
assertEquals(content, "Hello, Lynn.");
}
@Test
public void canAccessByServicePath() throws Exception {
HttpGet get = new HttpGet("http://localhost:8080/service/hello");
String content = EntityUtils.toString(client.execute(get).getEntity());
assertEquals(content, "Hello, Lynn.");
}
@AfterClass
public static void afterAll() throws Exception {
if(Objects.nonNull(server)) server.stop();
if(Objects.nonNull(client)) client.close();
}
@Path("/hello")
public static class MultipleContextHandlerResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello, Lynn.";
}
}
}
</code></pre>
</div>
</article>
<article class="post" itemprop="blogPost" itemscope itemtype="http://schema.org/BlogPosting">
<div class="meta">
<div class="date">
<time datetime="2017-05-06T01:20:05+08:00" itemprop="datePublished">2017/5/6</time>
</div>
<div class="tags">posted in
<a class='category' href='java.html'>Java</a>
</div>
</div>
<h1 class="title" itemprop="name"><a href="why-we-need-to-disable-trace-method-and-how-to-disable-trace-in-embedded-jetty.html" itemprop="url">
Why we need to disable TRACE method and how to disable TRACE in Embedded Jetty</a></h1>
<div class="entry-content" itemprop="articleBody">
<p>This page show you why we need to disable TRACE HTTP method for security reason. And provide a sample project to show you how to disable TRACE in embedded Jetty.</p>
<h2 id="toc_0">Why we need to disable TRACE method</h2>
<p>Allowing TRACE method will leads to Cross-Site Tracking (a.k.a XST) problem. XST was found in 2003. It’s a very old topic and I can’t get any new discussion after searched in Google. But it’s good to disable TRACE for our server to avoid any redundant endpoint exposes to the danger world. </p>
<h3 id="toc_1">Avoid XST Attack</h3>
<p>As we all know, server will echo back all information when it receive TRACE request. “All information” means the cookies, the credential data and the server version etc. When user is visiting a malicious website, a hacker can read malicious data by calling a cross-site TRACE request.</p>
<h3 id="toc_2">Limit Information Expose to the World</h3>
<p>In the other case, we run an API server which user will not access by browser directly. It’s good practice to limit the information expose to the external world. Information like version may tell others which issue is ok to use to hack. If we don’t need TRACE (at lease in production environment), so disable it.</p>
<h2 id="toc_3">How to disable TRACE in Embedded Jetty</h2>
<p>By default Jetty enables TRACE and we need to disable it manually.<br/>
This <a href="https://github.com/lawrenceching/jetty-disable-trace/blob/master/src/main/java/me/imlc/example/jetty_disable_trace/Main.java#L65">GitHub project</a> shows you how to disable TRACE for embedded Jetty.</p>
<pre><code class="language-java">private Handler wrapWithSecurityHandler(Handler h){
Constraint disableTraceConstraint = new Constraint();
disableTraceConstraint.setName("Disable TRACE");
disableTraceConstraint.setAuthenticate(true);
ConstraintMapping mapping = new ConstraintMapping();
mapping.setConstraint(disableTraceConstraint);
mapping.setMethod("TRACE");
mapping.setPathSpec("/");
// omissionConstraint is to fix the warning log ""null has uncovered http methods for path: /
// No impact to disable TRACE if you do not add this constraint
// But if you're using the monitoring tool like Geneos, and your component requires keep production monitoring all green,
// You can try to add this omissionConstraint to fix the warning Jetty prints.
Constraint omissionConstraint = new Constraint();
ConstraintMapping omissionMapping = new ConstraintMapping();
omissionMapping.setConstraint(omissionConstraint);
omissionMapping.setMethod("*");
omissionMapping.setPathSpec("/");
ConstraintSecurityHandler handler = new ConstraintSecurityHandler();
handler.addConstraintMapping(mapping);
handler.addConstraintMapping(omissionMapping);
handler.setHandler(h);
return handler;
}
</code></pre>
<p>Also notice that I wrote omissionConstraint, applied to all method to fix a warning Jetty prints:<br/>
<code>null has uncovered http methods for path: /</code></p>
<p>If you’r not required to keep production monitoring all green, you can delete this redundant constraint and accept this warning. </p>
<h6 id="toc_4">References</h6>
<p>[1] <a href="http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf">CROSS-SITE TRACING (XST) - THE NEW TECHNIQUES AND EMERGING THREATS TO BYPASS CURRENT WEB SECURITY MEASURES USING TRACE AND XSS - Jeremiah Grossman</a><br/>
[2] <a href="https://www.owasp.org/index.php/Cross_Site_Tracing">Cross Site Tracing - OWASP</a><br/>
[3] <a href="http://stackoverflow.com/questions/29348328/java-embedded-jetty-is-accepting-http-trace-method">spring - Java embedded jetty is accepting HTTP TRACE method - Stack Overflow</a></p>
</div>
</article>
<article class="post" itemprop="blogPost" itemscope itemtype="http://schema.org/BlogPosting">
<div class="meta">
<div class="date">
<time datetime="2016-09-27T18:17:56+08:00" itemprop="datePublished">2016/9/27</time>
</div>
<div class="tags">posted in
<a class='category' href='java.html'>Java</a>
</div>
</div>
<h1 class="title" itemprop="name"><a href="java-integer-%E7%BC%93%E5%AD%98-%E6%9C%BA%E5%88%B6-%E5%9D%91%E7%82%B9.html" itemprop="url">
Java Integer 缓存机制的小坑点</a></h1>
<div class="entry-content" itemprop="articleBody">
<p>Integer 是 Java 5 引入的新特性,该特性能节省内存和改善性能。同样被引入缓存机制的还有 Byte,Short,Long,Character,缓存范围都是在 [-128,127] (Character是在[0,127])之间。</p>
<p>但是有几点需要注意的是:<br/>
1. 对 Integer 对象引入了 IntegerCache 类,其他封装类型也有对应的 XxxCache。<br/>
2. 该缓存特性只有在 autoboxing 过程中使用,换言之,使用 constructor 创建的 Integer 并不能被缓存。<br/>
3. 因为缓存机制的存在,在缓存范围内的对象都来自同一个缓存。带来的副作用是使用“==”地址比较运算符比较两个看似不一样的对象,得到的是 true。网上其他文章的说法是因而可以使用 == 来比较直接比较两个对象的值。但我觉得这样理解容易造成偏差。Java 规范并没有约定 [-128,127] 的范围内 == 用作值比较,这只是一个副作用。<br/>
4. 只有 Integer 对象可以通过指定 JVM 启动参数来修改缓存上限。</p>
<pre><code>-XX:AutoBoxCacheMax=size
</code></pre>
<p>所以说写代码的时候还是不要把==用作值比较。<br/>
<br/>
老实说这个缓存特性带来的不一致性要是导致了什么BUG实在很难排查。当用了这个特性写了点什么之后,难保后来者不会产生迷惑。所以日常编码中还是尽量避开这个点。<br/>
<br/>
简单到爆的实验代码:<br/>
简单地验证Java Integer缓存特性</p>
<pre><code>import com.sun.istack.internal.NotNull;
/**
* Created by Lawrence on 15/11/9.
*/
public class Main {
public static void main(String[] argv){
Integer int1 = 100;
Integer int2 = 100;
if(int1==int2){
print("int1 is equal to int2");
} else {
print("int1 is not equal to int2");
}
// prints "int1 is equal to int2"
Integer int3 = 2333;
Integer int4 = 2333;
if(int3==int4){
print("int3 is equal to int4");
} else {
print("int3 is not equal to int4");
}
// prints "int3 is not equal to int4"
Integer int5 = 100;
Integer int6 = new Integer(100);
if(int5==int6){
print("int5 is equal to int6");
} else {
print("int5 is not equal to int6");
}
// prints "int5 is not equal to int6"
}
public static void print(String str){
System.out.println(str);
}
}
</code></pre>
</div>
</article>
</div>
<nav id="pagenavi">
<div class="center"><a href="archives.html">Blog Archives</a></div>
</nav>
</div>
</div>
<footer id="footer" class="inner">Copyright © 2018
Powered by <a target="_blank" href="http://www.mweb.im">MWeb</a>
Theme by <a href="http://shashankmehta.in/archive/2012/greyshade.html">Shashank Mehta</a>
<a href="http://www.miitbeian.gov.cn" target="_blank">粤ICP备15018861号</a>
</footer>
</div>
</div>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-57304811-3', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>