├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── allocations
├── README.md
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── github
│ │ └── chrishantha
│ │ └── sample
│ │ └── allocations
│ │ └── AllocationsApplication.java
│ └── resources
│ └── META-INF
│ └── services
│ └── com.github.chrishantha.sample.base.SampleApplication
├── base
├── README.md
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── github
│ └── chrishantha
│ └── sample
│ └── base
│ ├── App.java
│ ├── SampleApplication.java
│ └── Utils.java
├── deadlock
├── README.md
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── github
│ │ └── chrishantha
│ │ └── sample
│ │ └── deadlock
│ │ └── DeadlockApplication.java
│ └── resources
│ └── META-INF
│ └── services
│ └── com.github.chrishantha.sample.base.SampleApplication
├── highcpu
├── README.md
├── flame-graphs
│ ├── highcpu-jfr.svg
│ └── highcpu-perf.svg
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── github
│ │ └── chrishantha
│ │ └── sample
│ │ └── highcpu
│ │ ├── HashingWorker.java
│ │ ├── HighCpuApplication.java
│ │ ├── MathWorker.java
│ │ └── SleepingWorker.java
│ └── resources
│ └── META-INF
│ └── services
│ └── com.github.chrishantha.sample.base.SampleApplication
├── hotmethods
├── README.md
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── github
│ │ └── chrishantha
│ │ └── sample
│ │ └── hotmethods
│ │ └── HotMethodsApplication.java
│ └── resources
│ └── META-INF
│ └── services
│ └── com.github.chrishantha.sample.base.SampleApplication
├── latencies
├── README.md
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── github
│ │ └── chrishantha
│ │ └── sample
│ │ └── latencies
│ │ └── LatenciesApplication.java
│ └── resources
│ └── META-INF
│ └── services
│ └── com.github.chrishantha.sample.base.SampleApplication
├── memoryleak
├── README.md
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── github
│ │ └── chrishantha
│ │ └── sample
│ │ └── memoryleak
│ │ ├── BadKey.java
│ │ ├── GoodKey.java
│ │ ├── Key.java
│ │ └── MemoryLeakApplication.java
│ └── resources
│ └── META-INF
│ └── services
│ └── com.github.chrishantha.sample.base.SampleApplication
├── memoryref
├── README.md
├── classes.png
├── objects.png
├── pom.xml
├── references.png
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── github
│ │ └── chrishantha
│ │ └── sample
│ │ └── memoryref
│ │ ├── A.java
│ │ ├── B.java
│ │ ├── Base.java
│ │ ├── C.java
│ │ ├── D.java
│ │ ├── E.java
│ │ ├── F.java
│ │ ├── G.java
│ │ ├── JavaAgent.java
│ │ └── MemoryRefApplication.java
│ └── resources
│ └── META-INF
│ └── services
│ └── com.github.chrishantha.sample.base.SampleApplication
├── pom.xml
└── threadleak
├── README.md
├── pom.xml
└── src
└── main
├── java
└── com
│ └── github
│ └── chrishantha
│ └── sample
│ └── threadleak
│ └── ThreadLeakApplication.java
└── resources
└── META-INF
└── services
└── com.github.chrishantha.sample.base.SampleApplication
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 |
3 | # Package Files #
4 | *.jar
5 | *.war
6 | *.ear
7 |
8 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
9 | hs_err_pid*
10 |
11 | #Maven
12 | target/
13 | dependency-reduced-pom.xml
14 |
15 | #Eclipse files
16 | .project
17 | .classpath
18 |
19 | #Idea Files
20 | .idea
21 | *.iml
22 |
23 | tmp/
24 | *.tmp
25 | *.bak
26 | *.swp
27 | *~.nib
28 | .settings/
29 | # Locally stored "Eclipse launch configurations"
30 | *.launch
31 |
32 | # Flight Recorder files
33 | *.jfr
34 |
35 | # Log files
36 | *.log
37 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | jdk:
3 | - openjdk8
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://travis-ci.org/chrishantha/sample-java-programs)
2 |
3 | Sample Java Programs
4 | ====================
5 |
6 | This repository contains some sample programs. All are Maven projects and can be run directly using "java -jar"
7 |
8 | ## How to build
9 |
10 | Run `mvn clean install` to build all sample programs
11 |
12 | ## License
13 |
14 | Copyright (C) 2015 M. Isuru Tharanga Chrishantha Perera
15 |
16 | Licensed under the Apache License, Version 2.0
17 |
--------------------------------------------------------------------------------
/allocations/README.md:
--------------------------------------------------------------------------------
1 | Sample to show allocations in a Java Flight Recording
2 | =====================================================
3 |
4 | This program checks whether a number is prime.
5 |
6 | Run the program and also make a profiling recording.
7 |
8 | ### How to run
9 | ```bash
10 | java -Xms64m -Xmx64m -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints -XX:+FlightRecorder -XX:StartFlightRecording=settings=profile,duration=30s,name=Allocations,filename=allocations.jfr -Xlog:jfr=info -jar target/allocations.jar
11 | ```
12 |
13 | ### Analyzing Java Flight Recording
14 |
15 | In Memory -> Allocation tab, you should see a high allocation rate.
16 |
17 | Also, see Memory -> Garbage Collections tab and check the frequency of GC events.
18 |
19 | ### Improving Performance
20 |
21 | Try the program again after changing `Long` types to primitive `long`.
22 |
--------------------------------------------------------------------------------
/allocations/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
19 |
20 |
21 | com.github.chrishantha.sample
22 | java-samples
23 | 0.0.2-SNAPSHOT
24 | ../pom.xml
25 |
26 |
27 | 4.0.0
28 | allocations
29 | jar
30 | allocations
31 |
32 |
33 |
34 | com.github.chrishantha.sample
35 | base
36 |
37 |
38 |
39 |
40 |
41 |
42 | org.apache.maven.plugins
43 | maven-shade-plugin
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/allocations/src/main/java/com/github/chrishantha/sample/allocations/AllocationsApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.allocations;
17 |
18 | import com.beust.jcommander.Parameter;
19 | import com.github.chrishantha.sample.base.SampleApplication;
20 |
21 | public class AllocationsApplication implements SampleApplication {
22 |
23 | @Parameter(names = "--max", description = "Max Numbers")
24 | private long max = 10_000_000L;
25 |
26 | private boolean isPrime(Long n) {
27 | //check if n is a multiple of 2
28 | if (n % 2 == 0) return false;
29 | //if not, then just check the odds
30 | for (int i = 3; i * i <= n; i += 2) {
31 | if (n % i == 0)
32 | return false;
33 | }
34 | return true;
35 | }
36 |
37 | @Override
38 | public void start() {
39 | Long primeCount = 0L;
40 | for (long i = 0; i < max; i++) {
41 | if (isPrime(i)) {
42 | primeCount++;
43 | }
44 | }
45 | System.out.format("Found %d prime numbers%n", primeCount);
46 | }
47 |
48 | @Override
49 | public String toString() {
50 | return "AllocationsApplication{" +
51 | "max=" + max +
52 | '}';
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/allocations/src/main/resources/META-INF/services/com.github.chrishantha.sample.base.SampleApplication:
--------------------------------------------------------------------------------
1 | com.github.chrishantha.sample.allocations.AllocationsApplication
--------------------------------------------------------------------------------
/base/README.md:
--------------------------------------------------------------------------------
1 | Base module for Sample Applications
2 | ===================================
3 |
4 | This module helps to write sample applications quickly by implementing
5 | `com.github.chrishantha.sample.base.SampleApplication` interface and registering the implementation class as a service
6 | in `META-INF/services/com.github.chrishantha.sample.base.SampleApplication`
7 |
--------------------------------------------------------------------------------
/base/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
19 |
20 |
21 | com.github.chrishantha.sample
22 | java-samples
23 | 0.0.2-SNAPSHOT
24 | ../pom.xml
25 |
26 |
27 | 4.0.0
28 | base
29 | jar
30 | base
31 |
32 |
33 |
34 | com.beust
35 | jcommander
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/base/src/main/java/com/github/chrishantha/sample/base/App.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.base;
17 |
18 | import com.beust.jcommander.JCommander;
19 | import com.beust.jcommander.Parameter;
20 | import com.beust.jcommander.ParameterException;
21 |
22 | import java.util.Iterator;
23 | import java.util.ServiceLoader;
24 |
25 | public class App {
26 |
27 | private static class CommonArgs {
28 | @Parameter(names = {"-h", "--help"}, description = "Display Help", help = true)
29 | private boolean help = false;
30 | }
31 |
32 | public static void main(String[] args) {
33 | // There should be only one application
34 | Iterator applicationIterator = ServiceLoader.load(SampleApplication.class).iterator();
35 | if (!applicationIterator.hasNext()) {
36 | throw new IllegalStateException("Could not load Sample Application");
37 | }
38 | SampleApplication sampleApplication = applicationIterator.next();
39 | CommonArgs commonArgs = new CommonArgs();
40 | final JCommander jcmdr = JCommander.newBuilder()
41 | .programName(sampleApplication.getClass().getSimpleName())
42 | .addObject(sampleApplication)
43 | .addObject(commonArgs)
44 | .build();
45 |
46 | try {
47 | jcmdr.parse(args);
48 | } catch (ParameterException ex) {
49 | System.err.println(ex.getMessage());
50 | return;
51 | }
52 |
53 | if (commonArgs.help) {
54 | jcmdr.usage();
55 | return;
56 | }
57 |
58 | System.out.println(sampleApplication);
59 | sampleApplication.start();
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/base/src/main/java/com/github/chrishantha/sample/base/SampleApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.base;
17 |
18 | public interface SampleApplication {
19 |
20 | void start();
21 |
22 | String toString();
23 | }
24 |
--------------------------------------------------------------------------------
/base/src/main/java/com/github/chrishantha/sample/base/Utils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.base;
17 |
18 | import java.util.Timer;
19 | import java.util.TimerTask;
20 |
21 | /**
22 | * Some basic utilities for sample applications
23 | */
24 | public class Utils {
25 |
26 | /**
27 | * Exit application after a given number of seconds.
28 | *
29 | * @param timeout Timeout in seconds
30 | */
31 | public static void exitApplication(int timeout) {
32 | if (timeout > 0) {
33 | final Timer timer = new Timer();
34 | timer.schedule(new TimerTask() {
35 | public void run() {
36 | System.out.println("Exiting now...");
37 | System.exit(0);
38 | }
39 | }, timeout * 1000);
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/deadlock/README.md:
--------------------------------------------------------------------------------
1 | Sample to show deadlocks in a Java Application
2 | ==============================================
3 |
4 | This sample application shows an example of a deadlock. Following is the definition of "deadlock" according to
5 | [Java Tutorial](https://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html)
6 |
7 | > Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
8 |
9 | In this application, there are two threads trying to acquire two locks.
10 |
11 | ### How to run
12 |
13 | The application will throw Out of Memory error after some time when you run the application with default parameters.
14 |
15 | `java -Xms1g -Xmx1g -jar target/deadlock.jar`
16 |
17 | ### How to detect a deadlock
18 |
19 | Take a thread dump (using `jstack ` command or `jcmd Thread.print`).
20 |
21 | The thread dump should show the Java level deadlock details as follows.
22 |
23 | ```
24 | Found one Java-level deadlock:
25 | =============================
26 | "Thread Group 1-2":
27 | waiting to lock monitor 0x00007f8ab4003a78 (object 0x00000000eaca1488, a java.lang.Object),
28 | which is held by "Thread Group 1-1"
29 | "Thread Group 1-1":
30 | waiting to lock monitor 0x00007f8ab4006518 (object 0x00000000eaca1498, a java.lang.Object),
31 | which is held by "Thread Group 1-2"
32 |
33 | Java stack information for the threads listed above:
34 | ===================================================
35 | "Thread Group 1-2":
36 | at com.github.chrishantha.sample.deadlock.DeadlockApplication$SampleLockThread.run(DeadlockApplication.java:54)
37 | - waiting to lock <0x00000000eaca1488> (a java.lang.Object)
38 | - locked <0x00000000eaca1498> (a java.lang.Object)
39 | "Thread Group 1-1":
40 | at com.github.chrishantha.sample.deadlock.DeadlockApplication$SampleLockThread.run(DeadlockApplication.java:54)
41 | - waiting to lock <0x00000000eaca1498> (a java.lang.Object)
42 | - locked <0x00000000eaca1488> (a java.lang.Object)
43 |
44 | Found 1 deadlock.
45 | ```
--------------------------------------------------------------------------------
/deadlock/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
19 |
20 |
21 | com.github.chrishantha.sample
22 | java-samples
23 | 0.0.2-SNAPSHOT
24 | ../pom.xml
25 |
26 |
27 | 4.0.0
28 | deadlock
29 | jar
30 | deadlock
31 |
32 |
33 |
34 | com.github.chrishantha.sample
35 | base
36 |
37 |
38 |
39 |
40 |
41 |
42 | org.apache.maven.plugins
43 | maven-shade-plugin
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/deadlock/src/main/java/com/github/chrishantha/sample/deadlock/DeadlockApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.deadlock;
17 |
18 | import com.beust.jcommander.Parameter;
19 | import com.github.chrishantha.sample.base.SampleApplication;
20 |
21 | public class DeadlockApplication implements SampleApplication {
22 |
23 | @Parameter(names = "--count", description = "Number of deadlocks")
24 | private int count = 1;
25 |
26 | @Parameter(names = "--delay", description = "Delay in milliseconds to start a new thread group")
27 | private int delay = 0;
28 |
29 | private static class SampleLockThread extends Thread {
30 |
31 | private final Object lock1;
32 | private final Object lock2;
33 |
34 | public SampleLockThread(final String name, final Object lock1, final Object lock2) {
35 | super(name);
36 | this.lock1 = lock1;
37 | this.lock2 = lock2;
38 | }
39 |
40 | @Override
41 | public void run() {
42 | System.out.format("%s: Acquiring lock : %s%n", getName(), lock1);
43 | synchronized (lock1) {
44 | System.out.format("%s: Acquired lock : %s%n", getName(), lock1);
45 | try {
46 | Thread.sleep(100);
47 | } catch (InterruptedException e) {
48 | e.printStackTrace();
49 | }
50 |
51 | System.out.format("%s: Acquiring lock : %s%n", getName(), lock2);
52 | synchronized (lock2) {
53 | System.out.format("%s: Acquired lock : %s%n", getName(), lock2);
54 |
55 | }
56 | }
57 | }
58 | }
59 |
60 | @Override
61 | public void start() {
62 | final String nameFormat = "Thread Group %2d-%d";
63 | for (int i = 1; i <= count; i++) {
64 | final Object lock1 = new Object();
65 | final Object lock2 = new Object();
66 | SampleLockThread t1 = new SampleLockThread(String.format(nameFormat, i, 1), lock1, lock2);
67 | SampleLockThread t2 = new SampleLockThread(String.format(nameFormat, i, 2), lock2, lock1);
68 | t1.start();
69 | t2.start();
70 | if (delay > 0) {
71 | try {
72 | Thread.sleep(delay);
73 | } catch (InterruptedException e) {
74 | e.printStackTrace();
75 | }
76 | }
77 | }
78 | }
79 |
80 | @Override
81 | public String toString() {
82 | return "DeadlockApplication{" +
83 | "count=" + count +
84 | ", delay=" + delay +
85 | '}';
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/deadlock/src/main/resources/META-INF/services/com.github.chrishantha.sample.base.SampleApplication:
--------------------------------------------------------------------------------
1 | com.github.chrishantha.sample.deadlock.DeadlockApplication
--------------------------------------------------------------------------------
/highcpu/README.md:
--------------------------------------------------------------------------------
1 | Sample program consuming high CPU usage
2 | =======================================
3 |
4 | A java program consuming high CPU usage. This program was inspired by a sample found in the article "[Identifying which Java Thread is consuming most CPU](http://code.nomad-labs.com/2010/11/18/identifying-which-java-thread-is-consuming-most-cpu/)"
5 |
6 | ### How to run
7 | ```bash
8 | java -Xms128m -Xmx128m -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints -XX:+FlightRecorder -XX:StartFlightRecording=settings=profile,duration=30s,name=HighCPU,filename=highcpu.jfr -Xlog:jfr=info -jar target/highcpu.jar
9 | ```
10 |
--------------------------------------------------------------------------------
/highcpu/flame-graphs/highcpu-jfr.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
780 |
--------------------------------------------------------------------------------
/highcpu/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
19 |
20 |
21 | com.github.chrishantha.sample
22 | java-samples
23 | 0.0.2-SNAPSHOT
24 | ../pom.xml
25 |
26 |
27 | 4.0.0
28 | highcpu
29 | jar
30 | highcpu
31 |
32 |
33 |
34 | com.github.chrishantha.sample
35 | base
36 |
37 |
38 |
39 |
40 |
41 |
42 | org.apache.maven.plugins
43 | maven-shade-plugin
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/highcpu/src/main/java/com/github/chrishantha/sample/highcpu/HashingWorker.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.highcpu;
17 |
18 | import java.security.MessageDigest;
19 | import java.security.NoSuchAlgorithmException;
20 | import java.util.UUID;
21 |
22 | public class HashingWorker implements Runnable {
23 |
24 | private final String algorithm;
25 | private final long length;
26 |
27 | private byte[] lastComputedHash;
28 |
29 | public HashingWorker(long length, String algorithm) {
30 | this.length = length;
31 | this.algorithm = algorithm;
32 | }
33 |
34 | @SuppressWarnings("InfiniteLoopStatement")
35 | @Override
36 | public void run() {
37 | while (true) {
38 | StringBuilder data = new StringBuilder();
39 |
40 | // Some random data
41 | for (int i = 0; i < length; i++) {
42 | data.append(UUID.randomUUID().toString());
43 | }
44 |
45 | MessageDigest digest;
46 | try {
47 | digest = MessageDigest.getInstance(algorithm);
48 | } catch (NoSuchAlgorithmException e) {
49 | throw new RuntimeException(e);
50 | }
51 |
52 | // Hash
53 | digest.update(data.toString().getBytes());
54 | byte[] computedHash = digest.digest();
55 | if (lastComputedHash != null && computedHash.length != lastComputedHash.length) {
56 | throw new IllegalStateException("Is the hash computation correct??");
57 | }
58 | lastComputedHash = computedHash;
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/highcpu/src/main/java/com/github/chrishantha/sample/highcpu/HighCpuApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.highcpu;
17 |
18 | import com.beust.jcommander.Parameter;
19 | import com.github.chrishantha.sample.base.SampleApplication;
20 | import com.github.chrishantha.sample.base.Utils;
21 |
22 | public class HighCpuApplication implements SampleApplication {
23 |
24 | @Parameter(names = "--run-hashing", description = "Run Hashing Worker", arity = 1)
25 | private boolean runHashing = true;
26 |
27 | @Parameter(names = "--run-sleeping", description = "Run Sleeping Worker", arity = 1)
28 | private boolean runSleeping = true;
29 |
30 | @Parameter(names = "--run-math", description = "Run Math Worker", arity = 1)
31 | private boolean runMath = true;
32 |
33 | @Parameter(names = "--hashing-workers", description = "Hashing Workers")
34 | private int hashingWorkers = 6;
35 |
36 | @Parameter(names = "--sleeping-workers", description = "Sleeping Workers")
37 | private int sleepingWorkers = 4;
38 |
39 | @Parameter(names = "--math-workers", description = "Math Workers")
40 | private int mathWorkers = 2;
41 |
42 | @Parameter(names = "--hash-data-length", description = "Hash Data Length")
43 | private long hashDataLength = 2000;
44 |
45 | @Parameter(names = "--hashing-algo", description = "Hashing Algorithm")
46 | private String hashingAlgorithm = "SHA-1";
47 |
48 | @Parameter(names = "--exit-timeout", description = "Exit Timeout in Seconds (Default 2 minutes. Use 0 to run forever)")
49 | private int exitTimeoutInSeconds = 2 * 60;
50 |
51 | @Override
52 | public void start() {
53 | System.out.println("Starting Application...");
54 | Utils.exitApplication(exitTimeoutInSeconds);
55 | if (runHashing) {
56 | for (int i = 0; i < hashingWorkers; i++) {
57 | startThread(i, "Hashing", new HashingWorker(hashDataLength, hashingAlgorithm));
58 | }
59 | }
60 | if (runSleeping) {
61 | for (int i = 0; i < sleepingWorkers; i++) {
62 | startThread(i, "Sleeping", new SleepingWorker());
63 | }
64 | }
65 | if (runMath) {
66 | for (int i = 0; i < mathWorkers; i++) {
67 | startThread(i, "Math", new MathWorker());
68 | }
69 | }
70 | }
71 |
72 | private void startThread(int i, String name, Runnable worker) {
73 | Thread thread = new Thread(worker);
74 | thread.setName(String.format("Thread %d: %s", i, name));
75 | thread.start();
76 | }
77 |
78 | @Override
79 | public String toString() {
80 | return "HighCpuApplication{" +
81 | "runHashing=" + runHashing +
82 | ", runSleeping=" + runSleeping +
83 | ", runMath=" + runMath +
84 | ", hashingWorkers=" + hashingWorkers +
85 | ", sleepingWorkers=" + sleepingWorkers +
86 | ", mathWorkers=" + mathWorkers +
87 | ", hashDataLength=" + hashDataLength +
88 | ", hashingAlgorithm='" + hashingAlgorithm + '\'' +
89 | ", exitTimeoutInSeconds=" + exitTimeoutInSeconds +
90 | '}';
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/highcpu/src/main/java/com/github/chrishantha/sample/highcpu/MathWorker.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.highcpu;
17 |
18 | import java.math.BigDecimal;
19 | import java.util.Random;
20 |
21 | public class MathWorker implements Runnable {
22 |
23 | private Random random = new Random();
24 |
25 | @SuppressWarnings("InfiniteLoopStatement")
26 | @Override
27 | public void run() {
28 | BigDecimal bigDecimal = BigDecimal.ZERO;
29 | while (true) {
30 | double value = Math.atan(Math.sqrt(Math.pow(random.nextInt(10), random.nextDouble())));
31 | if (random.nextInt(10) > 5) {
32 | bigDecimal = bigDecimal.add(BigDecimal.valueOf(value));
33 | } else {
34 | bigDecimal = bigDecimal.subtract(BigDecimal.valueOf(value));
35 | }
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/highcpu/src/main/java/com/github/chrishantha/sample/highcpu/SleepingWorker.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.highcpu;
17 |
18 | import java.util.Random;
19 |
20 | public class SleepingWorker implements Runnable {
21 |
22 | private Random random = new Random();
23 |
24 | @SuppressWarnings("InfiniteLoopStatement")
25 | @Override
26 | public void run() {
27 | Long l = 0L;
28 | while (true) {
29 | l++;
30 | try {
31 | Thread.sleep(random.nextInt(20));
32 | } catch (InterruptedException e) {
33 | e.printStackTrace();
34 | }
35 | if (l == Long.MAX_VALUE) {
36 | l = 0L;
37 | }
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/highcpu/src/main/resources/META-INF/services/com.github.chrishantha.sample.base.SampleApplication:
--------------------------------------------------------------------------------
1 | com.github.chrishantha.sample.highcpu.HighCpuApplication
--------------------------------------------------------------------------------
/hotmethods/README.md:
--------------------------------------------------------------------------------
1 | Sample to show hot methods in a Java Flight Recording
2 | =====================================================
3 |
4 | This program checks whether a given random number is primitive or not.
5 |
6 | Run the program and also make a profiling recording.
7 |
8 | ### How to run
9 | ```bash
10 | java -Xms64m -Xmx64m -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints -XX:+FlightRecorder -XX:StartFlightRecording=settings=profile,duration=60s,name=Hotmethods,filename=hotmethods.jfr -Xlog:jfr=info -jar target/hotmethods.jar
11 | ```
12 |
13 | ### Analyzing Java Flight Recording
14 |
15 | In Code -> Hot Methods tab, you should see that the program has spent a lot of time in the LinkedList.indexOf(Object) method, which is called from contains method.
16 |
17 | ### Improving Performance
18 |
19 | By changing LinkedList to a HashSet, you can make the program run a lot faster.
20 |
21 | The contains methods in Linked List checks all the items. Algorithm run time is O(n). However the HashSet contains algorithm's run time is O(1).
22 |
23 | In the program, change `Collection primeNumbers = new LinkedList<>()` to `Collection primeNumbers = new HashSet<>()` to use a HashSet for Prime Numbers
24 |
25 | Check the runtime using HashSet.
26 |
27 | Use `time` command in Linux to measure the time.
28 |
--------------------------------------------------------------------------------
/hotmethods/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
19 |
20 |
21 | com.github.chrishantha.sample
22 | java-samples
23 | 0.0.2-SNAPSHOT
24 | ../pom.xml
25 |
26 |
27 | 4.0.0
28 | hotmethods
29 | jar
30 | hotmethods
31 |
32 |
33 |
34 | com.github.chrishantha.sample
35 | base
36 |
37 |
38 |
39 |
40 |
41 |
42 | org.apache.maven.plugins
43 | maven-shade-plugin
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/hotmethods/src/main/java/com/github/chrishantha/sample/hotmethods/HotMethodsApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.hotmethods;
17 |
18 | import com.beust.jcommander.Parameter;
19 | import com.github.chrishantha.sample.base.SampleApplication;
20 |
21 | import java.util.Collection;
22 | import java.util.LinkedList;
23 | import java.util.Random;
24 |
25 | public class HotMethodsApplication implements SampleApplication {
26 |
27 | @Parameter(names = "--count", description = "Random Numbers Count")
28 | private int randomNumbersCount = 1000000;
29 |
30 | @Parameter(names = "--max", description = "Maximum limit to generate prime numbers")
31 | private int max = 100000;
32 |
33 | @Override
34 | public void start() {
35 | Collection primeNumbers = new LinkedList<>();
36 | System.out.println("Generating Prime numbers between 1 and " + max);
37 | for (int i = 1; i < max; i++) {
38 | boolean isPrimeNumber = true;
39 | // Check whether the number is prime
40 | for (int j = 2; j < i; j++) {
41 | if (i % j == 0) {
42 | isPrimeNumber = false;
43 | break;
44 | }
45 | }
46 |
47 | if (isPrimeNumber) {
48 | primeNumbers.add(i);
49 | }
50 | }
51 |
52 | Random random = new Random();
53 | System.out.println("Checking Random Prime numbers");
54 | int count = 0;
55 | for (int i = 1; i < randomNumbersCount; i++) {
56 | int randomNumber = random.nextInt(max);
57 | if (primeNumbers.contains(randomNumber)) {
58 | count++;
59 | }
60 | }
61 | System.out.format("Found %d prime numbers from %d random numbers%n", count, randomNumbersCount);
62 | }
63 |
64 | @Override
65 | public String toString() {
66 | return "HotMethodsApplication{" +
67 | "randomNumbersCount=" + randomNumbersCount +
68 | ", max=" + max +
69 | '}';
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/hotmethods/src/main/resources/META-INF/services/com.github.chrishantha.sample.base.SampleApplication:
--------------------------------------------------------------------------------
1 | com.github.chrishantha.sample.hotmethods.HotMethodsApplication
--------------------------------------------------------------------------------
/latencies/README.md:
--------------------------------------------------------------------------------
1 | Sample to show latencies in a Java Flight Recording
2 | ===================================================
3 |
4 | This program has two threads: Even and Odd to print Even and Odd numbers.
5 |
6 | Run the program and also make a profiling recording.
7 |
8 | ### How to run
9 | ```bash
10 | java -Xms64m -Xmx64m -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints -XX:+FlightRecorder -XX:StartFlightRecording=settings=profile,duration=30s,name=Latencies,filename=latencies.jfr -Xlog:jfr=info -jar target/latencies.jar
11 | ```
12 |
13 | ### Analyzing Java Flight Recording
14 |
15 | In Threads -> Latencies tab, you should see that the program has many blocked events.
16 |
17 | You should also see red blocks in Events -> Graph tab. Red blocks are not good as the thread is just waiting to acquire a lock.
18 |
19 | See Threads -> Contention tab to see the Locks and also see Threads -> Lock Instances to check whether both threads share the same lock instances.
20 |
21 | ### Improving Performance
22 |
23 | Since there is no shared resource to protect, you can avoid the synchronized keyword and improve the performance.
24 |
25 | Try the program again after removing the `synchronized` keyword in `isEven` method.
26 |
--------------------------------------------------------------------------------
/latencies/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
19 |
20 |
21 | com.github.chrishantha.sample
22 | java-samples
23 | 0.0.2-SNAPSHOT
24 | ../pom.xml
25 |
26 |
27 | 4.0.0
28 | latencies
29 | jar
30 | latencies
31 |
32 |
33 |
34 | com.github.chrishantha.sample
35 | base
36 |
37 |
38 |
39 |
40 |
41 |
42 | org.apache.maven.plugins
43 | maven-shade-plugin
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/latencies/src/main/java/com/github/chrishantha/sample/latencies/LatenciesApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.latencies;
17 |
18 | import com.beust.jcommander.Parameter;
19 | import com.github.chrishantha.sample.base.SampleApplication;
20 |
21 | public class LatenciesApplication implements SampleApplication {
22 |
23 | @Parameter(names = "--count", description = "Print Count")
24 | private int count = 50;
25 |
26 | private class EvenThread extends Thread {
27 |
28 | public EvenThread() {
29 | super("Even-Thread");
30 | }
31 |
32 | @Override
33 | public void run() {
34 | for (int i = 0; i < count; i++) {
35 | if (isEven(i)) {
36 | printNumber(i);
37 | }
38 | }
39 | }
40 | }
41 |
42 | private class OddThread extends Thread {
43 |
44 | public OddThread() {
45 | super("Odd-Thread");
46 | }
47 |
48 | @Override
49 | public void run() {
50 | for (int i = 0; i < count; i++) {
51 | if (!isEven(i)) {
52 | printNumber(i);
53 | }
54 | }
55 | }
56 | }
57 |
58 |
59 | private void printNumber(int i) {
60 | System.out.format("Thread: %s, Number: %d%n", Thread.currentThread().getName(), i);
61 | }
62 |
63 | private synchronized boolean isEven(int i) {
64 | try {
65 | Thread.sleep(1000);
66 | } catch (InterruptedException e) {
67 | e.printStackTrace();
68 | }
69 | return i % 2 == 0;
70 | }
71 |
72 | @Override
73 | public void start() {
74 | new EvenThread().start();
75 | new OddThread().start();
76 | }
77 |
78 | @Override
79 | public String toString() {
80 | return "LatenciesApplication{" +
81 | "count=" + count +
82 | '}';
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/latencies/src/main/resources/META-INF/services/com.github.chrishantha.sample.base.SampleApplication:
--------------------------------------------------------------------------------
1 | com.github.chrishantha.sample.latencies.LatenciesApplication
--------------------------------------------------------------------------------
/memoryleak/README.md:
--------------------------------------------------------------------------------
1 | Sample to show a memory leak in Java Application
2 | ================================================
3 |
4 | This sample application implements a simple caching solution using a `HashMap`.
5 |
6 | For example, see following code.
7 |
8 | Map map = new HashMap<>();
9 | while (true) {
10 | for (int i = 0; i < max; i++) {
11 | Key key = new Key(i);
12 | if (!map.containsKey(key)) {
13 | map.put(key, "Number:" + i);
14 | }
15 | }
16 | }
17 |
18 | The map is not expected to grow beyond `max` value as all keys will be there in the map after the first `while` loop.
19 |
20 | However, if the `Key` class does not contain a proper `equals()` implementation along with the `hashCode()`
21 | implementation, the key elements will be keep getting added as the `!map.containsKey(key)` will always return `false`.
22 | This is a good example of a memory leak and this sample was inspired by the blog post:
23 | "[How to create a memory leak](https://plumbr.io/blog/memory-leaks/how-to-create-a-memory-leak)"
24 |
25 | ### How to run
26 |
27 | The application will throw Out of Memory error after some time when you run following command
28 |
29 | `java -Xms1g -Xmx1g -XX:+PrintGCDetails -XX:+PrintGC -XX:+PrintGCDateStamps -Xloggc:gc.log
30 | -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath="/tmp/heap-dump.hprof"
31 | -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints
32 | -XX:+UnlockCommercialFeatures -XX:+FlightRecorder
33 | -XX:StartFlightRecording=settings=profile,duration=5m,name=MemoryLeak,filename=memoryleak.jfr
34 | -XX:FlightRecorderOptions=loglevel=info
35 | -jar target/memoryleak.jar`
36 |
37 | ### Analyzing Java Flight Recording
38 |
39 | In Memory -> Memory tab, you should see a high memory growth rate.
40 |
41 | Also see Memory -> Garbage Collections tab and check the frequency of GC events.
42 |
43 | ### Analyzing Garbage Collection Logs (GC)
44 |
45 | You can analyze the GC logs using [GCViewer](https://github.com/chewiebug/GCViewer)
46 |
47 | ### How to fix the Memory Leak
48 |
49 | Run the application with `--key-type GOOD` parameter, which will use a Key object with proper `equals()` implementation.
50 |
--------------------------------------------------------------------------------
/memoryleak/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
19 |
20 |
21 | com.github.chrishantha.sample
22 | java-samples
23 | 0.0.2-SNAPSHOT
24 | ../pom.xml
25 |
26 |
27 | 4.0.0
28 | memoryleak
29 | jar
30 | memoryleak
31 |
32 |
33 |
34 | com.github.chrishantha.sample
35 | base
36 |
37 |
38 |
39 |
40 |
41 |
42 | org.apache.maven.plugins
43 | maven-shade-plugin
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/memoryleak/src/main/java/com/github/chrishantha/sample/memoryleak/BadKey.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryleak;
17 |
18 | public class BadKey extends Key {
19 |
20 | public BadKey(long NUMBER, long LENGTH) {
21 | super(NUMBER, LENGTH);
22 | }
23 |
24 | @Override
25 | public boolean equals(Object o) {
26 | return super.equals(o);
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/memoryleak/src/main/java/com/github/chrishantha/sample/memoryleak/GoodKey.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryleak;
17 |
18 | import java.util.Objects;
19 |
20 | public class GoodKey extends Key {
21 |
22 | public GoodKey(long NUMBER, long LENGTH) {
23 | super(NUMBER, LENGTH);
24 | }
25 |
26 | @Override
27 | public boolean equals(Object o) {
28 | if (this == o) return true;
29 | if (o == null || getClass() != o.getClass()) return false;
30 | Key key = (Key) o;
31 | return Objects.equals(KEY, key.KEY);
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/memoryleak/src/main/java/com/github/chrishantha/sample/memoryleak/Key.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryleak;
17 |
18 | import java.util.Objects;
19 |
20 | public abstract class Key {
21 |
22 | protected final String KEY;
23 |
24 | public Key(final long NUMBER, final long LENGTH) {
25 | String binaryString = Long.toBinaryString(NUMBER);
26 | StringBuilder keyBuilder = new StringBuilder();
27 | long limit = LENGTH - binaryString.length();
28 | for (long i = 0; i < limit; i++) {
29 | keyBuilder.append('0');
30 | }
31 | keyBuilder.append(binaryString);
32 | KEY = keyBuilder.toString();
33 | }
34 |
35 | @Override
36 | public final int hashCode() {
37 | return Objects.hash(KEY);
38 | }
39 |
40 | @Override
41 | public final String toString() {
42 | StringBuilder builder = new StringBuilder();
43 | builder.append(this.getClass().getSimpleName());
44 | builder.append(" [key=");
45 | builder.append(KEY);
46 | builder.append("]");
47 | return builder.toString();
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/memoryleak/src/main/java/com/github/chrishantha/sample/memoryleak/MemoryLeakApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryleak;
17 |
18 | import com.beust.jcommander.Parameter;
19 | import com.github.chrishantha.sample.base.SampleApplication;
20 |
21 | import java.util.HashMap;
22 | import java.util.Map;
23 |
24 | public class MemoryLeakApplication implements SampleApplication {
25 |
26 | private enum KeyType {
27 | BAD,
28 | GOOD
29 | }
30 |
31 | @Parameter(names = "--length", description = "Length of the Key")
32 | private long length = 1024 * 1024;
33 |
34 | @Parameter(names = "--max", description = "Maximum limit to generate keys")
35 | private int max = 100;
36 |
37 | @Parameter(names = "--key-type", description = "Key Type: Good or Bad")
38 | private KeyType keyType = KeyType.BAD;
39 |
40 | @SuppressWarnings("InfiniteLoopStatement")
41 | @Override
42 | public void start() {
43 | Map map = new HashMap<>();
44 | while (true) {
45 | for (int i = 0; i < max; i++) {
46 | Key key = KeyType.GOOD.equals(keyType) ? new GoodKey(i, length) : new BadKey(i, length);
47 | if (!map.containsKey(key)) {
48 | map.put(key, "Number:" + i);
49 | }
50 | }
51 | }
52 | }
53 |
54 | @Override
55 | public String toString() {
56 | return "MemoryLeakApplication{" +
57 | "length=" + length +
58 | ", max=" + max +
59 | ", keyType=" + keyType +
60 | '}';
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/memoryleak/src/main/resources/META-INF/services/com.github.chrishantha.sample.base.SampleApplication:
--------------------------------------------------------------------------------
1 | com.github.chrishantha.sample.memoryleak.MemoryLeakApplication
--------------------------------------------------------------------------------
/memoryref/README.md:
--------------------------------------------------------------------------------
1 | Sample to a show memory references in a Java Application
2 | ========================================================
3 |
4 | This sample application creates objects from classes `A`, `B`, `C`, `D`, `E`, `F`, and `G`.
5 | Each of the previously mentioned classes extend to `Base` class, which creates a significantly
6 | large byte array in the constructor.
7 |
8 | Following is the class diagram.
9 |
10 | 
11 |
12 | The application is created to demonstrate the references among objects.
13 |
14 | The sample application creates an object from class `A` in the main thread and another object from
15 | class `G` in a daemon thread.
16 |
17 | The instance created from class `A` references the instances created from other classes as shown below.
18 |
19 | 
20 |
21 | Following is the object diagram showing the object references after the application is started.
22 |
23 | 
24 |
25 | ### How to run
26 |
27 | Use the following command to run the application. The application creates an object from class `A` in
28 | the main thread and another object from class `G` in a daemon thread. After that the application will
29 | wait for a keyboard input.
30 |
31 | ```bash
32 | java -Xmn1g -Xmx2g -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCDateStamps -javaagent:target/memoryref.jar -jar target/memoryref.jar
33 | ```
34 |
35 | ### Looking at object references using a Heap Dump.
36 |
37 | A heap dump can be obtained from following command to look at the object references in heap memory.
38 |
39 | ```bash
40 | jmap -dump:file=target/heap.hprof $(pgrep -f memoryref)
41 | ```
42 |
43 | Use [Eclipse Memory Analyzer Tool (MAT)](https://www.eclipse.org/mat/) to analyze the heap dump.
44 |
45 | For more information, read following story based on this sample application.
46 |
47 | [Basic concepts of Java heap dump analysis with Eclipse Memory Analyzer Tool (MAT)](https://medium.com/@chrishantha/basic-concepts-of-java-heap-dump-analysis-with-mat-e3615fd79eb)
48 |
49 | Note: Images were created using [draw.io](https://www.draw.io/).
50 |
--------------------------------------------------------------------------------
/memoryref/classes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrishantha/sample-java-programs/f688758a2df95f3d8dc59c296a473d8b52309f30/memoryref/classes.png
--------------------------------------------------------------------------------
/memoryref/objects.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrishantha/sample-java-programs/f688758a2df95f3d8dc59c296a473d8b52309f30/memoryref/objects.png
--------------------------------------------------------------------------------
/memoryref/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
19 |
20 |
21 | com.github.chrishantha.sample
22 | java-samples
23 | 0.0.2-SNAPSHOT
24 | ../pom.xml
25 |
26 |
27 | 4.0.0
28 | memoryref
29 | jar
30 | memoryref
31 |
32 |
33 |
34 | com.github.chrishantha.sample
35 | base
36 |
37 |
38 |
39 |
40 |
41 |
42 | org.apache.maven.plugins
43 | maven-shade-plugin
44 |
45 |
46 |
47 |
48 |
49 |
50 | com.github.chrishantha.sample.memoryref.JavaAgent
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
--------------------------------------------------------------------------------
/memoryref/references.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrishantha/sample-java-programs/f688758a2df95f3d8dc59c296a473d8b52309f30/memoryref/references.png
--------------------------------------------------------------------------------
/memoryref/src/main/java/com/github/chrishantha/sample/memoryref/A.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryref;
17 |
18 | public class A extends Base {
19 |
20 | final B b;
21 | final C c;
22 |
23 | A() {
24 | b = new B();
25 | c = new C(b);
26 | }
27 |
28 | @Override
29 | public long getSize() {
30 | return super.getSize() + b.getSize() + c.getSize();
31 | }
32 | }
--------------------------------------------------------------------------------
/memoryref/src/main/java/com/github/chrishantha/sample/memoryref/B.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryref;
17 |
18 | public class B extends Base {
19 |
20 | final D d;
21 | final E e;
22 |
23 | B() {
24 | d = new D();
25 | e = new E();
26 | }
27 |
28 | @Override
29 | public long getSize() {
30 | return super.getSize() + d.getSize() + e.getSize();
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/memoryref/src/main/java/com/github/chrishantha/sample/memoryref/Base.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryref;
17 |
18 | import java.util.Random;
19 |
20 | public abstract class Base {
21 |
22 | private final byte[] bytes;
23 | private static final Random random = new Random();
24 |
25 | Base() {
26 | bytes = new byte[(10 * (1 + random.nextInt(10))) * 1024 * 1024];
27 | }
28 |
29 | public long getSize() {
30 | return JavaAgent.getObjectSize(this) + JavaAgent.getObjectSize(bytes);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/memoryref/src/main/java/com/github/chrishantha/sample/memoryref/C.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryref;
17 |
18 | public class C extends Base {
19 |
20 | final E e;
21 | final F f;
22 |
23 | C(B b) {
24 | this.e = b.e;
25 | f = new F();
26 | }
27 |
28 | @Override
29 | public long getSize() {
30 | return super.getSize() + f.getSize();
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/memoryref/src/main/java/com/github/chrishantha/sample/memoryref/D.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryref;
17 |
18 | public class D extends Base {
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/memoryref/src/main/java/com/github/chrishantha/sample/memoryref/E.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryref;
17 |
18 | public class E extends Base {
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/memoryref/src/main/java/com/github/chrishantha/sample/memoryref/F.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryref;
17 |
18 | public class F extends Base {
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/memoryref/src/main/java/com/github/chrishantha/sample/memoryref/G.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryref;
17 |
18 | public class G extends Base {
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/memoryref/src/main/java/com/github/chrishantha/sample/memoryref/JavaAgent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryref;
17 |
18 | import java.lang.instrument.Instrumentation;
19 |
20 | public class JavaAgent {
21 | private static volatile Instrumentation instrumentation;
22 |
23 | public static void premain(final String agentArgs, final Instrumentation instrumentation) {
24 | JavaAgent.instrumentation = instrumentation;
25 | }
26 |
27 | public static long getObjectSize(final Object object) {
28 | if (instrumentation == null) {
29 | return -1L;
30 | }
31 | return instrumentation.getObjectSize(object);
32 | }
33 | }
--------------------------------------------------------------------------------
/memoryref/src/main/java/com/github/chrishantha/sample/memoryref/MemoryRefApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.memoryref;
17 |
18 | import com.github.chrishantha.sample.base.SampleApplication;
19 |
20 | import java.io.IOException;
21 |
22 | public class MemoryRefApplication implements SampleApplication {
23 |
24 | @Override
25 | public void start() {
26 | A a = new A();
27 | long size = a.getSize();
28 | System.out.format("The retained heap size of object A is %d bytes (~%d MiB).%n",
29 | size, (size / (1024 * 1024)));
30 | long objectSize = JavaAgent.getObjectSize(a);
31 | if (objectSize > 0) {
32 | System.out.format("The shallow heap size of object A is %d bytes.%n", objectSize);
33 | } else {
34 | System.out.println("WARNING: Java Agent is not initialized properly.");
35 | }
36 | Thread backgroundThread = new Thread() {
37 |
38 | private long getSize() {
39 | G g = new G();
40 | return g.getSize();
41 | }
42 |
43 | @Override
44 | public void run() {
45 | long size = getSize();
46 | System.out.format("The size of object allocated within the background thread was %d bytes (~%d MiB).%n",
47 | size, (size / (1024 * 1024)));
48 | try {
49 | Thread.sleep(Long.MAX_VALUE);
50 | } catch (InterruptedException e) {
51 | e.printStackTrace();
52 | }
53 | }
54 | };
55 | backgroundThread.setName("Background Thread");
56 | backgroundThread.setDaemon(true);
57 | backgroundThread.start();
58 | try {
59 | System.out.println("Press Enter to exit.");
60 | System.in.read();
61 | } catch (IOException e) {
62 | e.printStackTrace();
63 | }
64 | }
65 |
66 | @Override
67 | public String toString() {
68 | return "MemoryRefApplication";
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/memoryref/src/main/resources/META-INF/services/com.github.chrishantha.sample.base.SampleApplication:
--------------------------------------------------------------------------------
1 | com.github.chrishantha.sample.memoryref.MemoryRefApplication
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
19 | 4.0.0
20 |
21 | com.github.chrishantha.sample
22 | java-samples
23 | 0.0.2-SNAPSHOT
24 | pom
25 |
26 | Java Samples
27 | Java Sample Code to be used in examples (in blog, etc)
28 | 2015
29 |
30 |
31 |
32 | The Apache Software License, Version 2.0
33 | http://www.apache.org/licenses/LICENSE-2.0.txt
34 | repo
35 |
36 |
37 |
38 |
39 | https://github.com/chrishantha/sample-java-programs.git
40 | scm:git:https://github.com/chrishantha/sample-java-programs.git
41 | scm:git:https://github.com/chrishantha/sample-java-programs.git
42 | HEAD
43 |
44 |
45 |
46 | base
47 | highcpu
48 | hotmethods
49 | latencies
50 | allocations
51 | deadlock
52 | memoryleak
53 | threadleak
54 | memoryref
55 |
56 |
57 |
58 |
59 |
60 | com.beust
61 | jcommander
62 | ${jcommander.version}
63 |
64 |
65 | com.github.chrishantha.sample
66 | base
67 | ${samples.version}
68 |
69 |
70 | org.hdrhistogram
71 | HdrHistogram
72 | ${hdrhistogram.version}
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 | org.apache.maven.plugins
82 | maven-shade-plugin
83 | 3.5.2
84 |
85 |
86 |
87 | shade
88 |
89 |
90 |
91 |
93 | com.github.chrishantha.sample.base.App
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 | org.apache.maven.plugins
105 | maven-compiler-plugin
106 | 3.13.0
107 |
108 | ${javac.target}
109 | ${javac.target}
110 | ${javac.target}
111 |
112 |
113 |
114 | org.apache.maven.plugins
115 | maven-enforcer-plugin
116 | 3.4.1
117 |
118 |
119 | enforce-maven
120 |
121 | enforce
122 |
123 |
124 |
125 |
126 | 3.9
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 | ${project.name}
135 |
136 |
137 |
138 |
139 | pedantic
140 |
141 |
142 |
143 | org.apache.rat
144 | apache-rat-plugin
145 | 0.16.1
146 |
147 |
148 | **/README.md
149 | .travis.yml
150 | **/*.svg
151 | dependency-reduced-pom.xml
152 | **/com.github.chrishantha.sample.base.SampleApplication
153 |
154 |
155 |
156 |
157 | verify
158 |
159 | check
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 | UTF-8
171 | 1.8
172 | 0.0.2-SNAPSHOT
173 | 1.82
174 | 2.1.12
175 |
176 |
177 |
--------------------------------------------------------------------------------
/threadleak/README.md:
--------------------------------------------------------------------------------
1 | Sample to show thread leaks in a Java Application
2 | =================================================
3 |
4 | This sample application implements merge sort algorithm using multiple threads.
5 |
6 | The algorithm for parallel merge sort was taken from the [Merge Sort example available online from the University
7 | of Washington](https://courses.cs.washington.edu/courses/cse373/13wi/lectures/03-13/MergeSort.java)
8 |
9 | The original example uses threads directly. This sample application uses an `ExecutorService` to run threads.
10 |
11 | This application runs continuously and prints an interval summary statistics of algorithm run time for multiple random
12 | number arrays. The application will also print final summary statistics of algorithm run time at the program exit.
13 |
14 | ### How to run
15 |
16 | The application will throw Out of Memory error after some time when you run following command
17 |
18 | `java -Xmx1g -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints
19 | -XX:+UnlockCommercialFeatures -XX:+FlightRecorder
20 | -XX:StartFlightRecording=settings=profile,duration=2m,name=ThreadLeak,filename=threadleak.jfr
21 | -XX:FlightRecorderOptions=loglevel=info
22 | -jar target/threadleak.jar`
23 |
24 | ### Analyzing Java Flight Recording
25 |
26 | In Threads -> Overview tab, you should see thread count is increasing steadily.
27 |
28 | ### How to fix the Thread Leak
29 |
30 | Run the application with `--stop-leakage` parameter, which will use a single `ExecutorService` throughout the
31 | application.
32 |
--------------------------------------------------------------------------------
/threadleak/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
19 |
20 |
21 | com.github.chrishantha.sample
22 | java-samples
23 | 0.0.2-SNAPSHOT
24 | ../pom.xml
25 |
26 |
27 | 4.0.0
28 | threadleak
29 | jar
30 | threadleak
31 |
32 |
33 |
34 | com.github.chrishantha.sample
35 | base
36 |
37 |
38 | org.hdrhistogram
39 | HdrHistogram
40 |
41 |
42 |
43 |
44 |
45 |
46 | org.apache.maven.plugins
47 | maven-shade-plugin
48 |
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/threadleak/src/main/java/com/github/chrishantha/sample/threadleak/ThreadLeakApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 M. Isuru Tharanga Chrishantha Perera
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.chrishantha.sample.threadleak;
17 |
18 | import com.beust.jcommander.Parameter;
19 | import com.github.chrishantha.sample.base.SampleApplication;
20 | import com.github.chrishantha.sample.base.Utils;
21 | import org.HdrHistogram.Histogram;
22 | import org.HdrHistogram.Recorder;
23 |
24 | import java.lang.management.ManagementFactory;
25 | import java.lang.management.ThreadMXBean;
26 | import java.time.LocalDateTime;
27 | import java.time.format.DateTimeFormatter;
28 | import java.util.Arrays;
29 | import java.util.Map;
30 | import java.util.Random;
31 | import java.util.Timer;
32 | import java.util.TimerTask;
33 | import java.util.concurrent.ConcurrentSkipListMap;
34 | import java.util.concurrent.ExecutorService;
35 | import java.util.concurrent.Executors;
36 | import java.util.concurrent.Future;
37 |
38 | @SuppressWarnings("FieldCanBeLocal")
39 | public class ThreadLeakApplication implements SampleApplication {
40 |
41 | // Random number generator
42 | private static final Random random = new Random();
43 |
44 | // Get the Thread MXBean.
45 | private final static ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
46 |
47 | // Formatter to print current time
48 | private final static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
49 |
50 | @Parameter(names = "--threads", description = "Number of threads to be used for merge sorting algorithm.")
51 | private int threads = Runtime.getRuntime().availableProcessors();
52 |
53 | @Parameter(names = "--initial-length", description = "Initial length of random number array to sort.")
54 | private int length = 1_000;
55 |
56 | @Parameter(names = "--runs", description = "How many times to grow the array by 2")
57 | private int runs = 16;
58 |
59 | @Parameter(names = "--bound", description = "Upper bound of values in array.")
60 | private int bound = 1_000_000;
61 |
62 | @Parameter(names = "--delay", description = "Initial delay in seconds to print statistics. Default: 10 seconds.")
63 | private int delay = 10;
64 |
65 | @Parameter(names = "--period", description = "Period in seconds to print statistics. Default: 30 seconds.")
66 | private int period = 30;
67 |
68 | @Parameter(names = "--stop-leakage", description = "Stop leaking threads.", arity = 0)
69 | private boolean stopLeakage = false;
70 |
71 | @Parameter(names = "--exit-timeout", description = "Exit timeout in seconds " +
72 | "(Default 2 minutes. Use 0 to run forever)")
73 | private int exitTimeoutInSeconds = 2 * 60;
74 |
75 | private volatile ExecutorService executorService;
76 |
77 | @SuppressWarnings("InfiniteLoopStatement")
78 | @Override
79 | public void start() {
80 | System.out.println("Starting Application...");
81 | Utils.exitApplication(exitTimeoutInSeconds);
82 |
83 | // Map of stats for each array size used for merge sorting
84 | final Map recorderMap = new ConcurrentSkipListMap<>();
85 |
86 | // Schedule the printing of statistics
87 | final Timer timer = new Timer();
88 | timer.schedule(new TimerTask() {
89 | public void run() {
90 | printHeader("Interval");
91 | for (Map.Entry entry : recorderMap.entrySet()) {
92 | StatsRecorder statsRecorder = entry.getValue();
93 | Histogram histogram = statsRecorder.recorder.getIntervalHistogram();
94 | statsRecorder.accumulatedHistogram.add(histogram);
95 | printRow(entry.getKey(), histogram);
96 | }
97 | }
98 | }, delay * 1000, period * 1000);
99 |
100 | // Print statistics at exit
101 | Runtime.getRuntime().addShutdownHook(new Thread(() -> {
102 | printHeader("Final");
103 | for (Map.Entry entry : recorderMap.entrySet()) {
104 | StatsRecorder statsRecorder = entry.getValue();
105 | Histogram histogram = statsRecorder.accumulatedHistogram;
106 | printRow(entry.getKey(), histogram);
107 | }
108 | }));
109 |
110 | // Run continuously.
111 | while (true) {
112 | // Initial array length
113 | int arrayLength = length;
114 | for (int i = 1; i <= runs; i++) {
115 | int[] numbers = createRandomArray(arrayLength);
116 |
117 | // run the algorithm and measure how long it takes
118 | long startTime = System.nanoTime();
119 | parallelMergeSort(numbers);
120 | long endTime = System.nanoTime();
121 | StatsRecorder statsRecorder = recorderMap.compute(arrayLength, (integer, existingRecorder) -> {
122 | if (existingRecorder != null) {
123 | return existingRecorder;
124 | } else {
125 | return new StatsRecorder();
126 | }
127 | });
128 | statsRecorder.recorder.recordValue(endTime - startTime);
129 |
130 | if (!isSorted(numbers)) {
131 | throw new RuntimeException("Array is not sorted: " + Arrays.toString(numbers));
132 | }
133 |
134 | arrayLength *= 2; // double size of array for next time
135 | }
136 | }
137 | }
138 |
139 | private static class StatsRecorder {
140 | // HdrHistogram recorder to record algorithm run time.
141 | Recorder recorder = new Recorder(2);
142 | // Accumulated values
143 | Histogram accumulatedHistogram = new Histogram(2);
144 | }
145 |
146 | private void printHeader(String summary) {
147 | System.out.printf("Time: %20s, Summary: %8s, Thread Count: %3d, Unit: milliseconds (ms)\n",
148 | LocalDateTime.now().format(formatter),
149 | summary,
150 | threadMXBean.getThreadCount());
151 | System.out.printf("%8s, %7s, " +
152 | "%7s, %7s, %7s, " +
153 | "%7s, %7s, " +
154 | "%7s, %7s, %7s, %7s\n",
155 | "Elements", "Samples",
156 | "Avg", "Min", "Max",
157 | "StdDev", "Median",
158 | "p75", "p98", "p99", "p99.9");
159 | }
160 |
161 | private void printRow(int elements, Histogram histogram) {
162 | System.out.printf("%8d, %7d," +
163 | " %7.2f, %7.2f, %7.2f," +
164 | " %7.2f, %7.2f, " +
165 | "%7.2f, %7.2f, %7.2f, %7.2f\n", elements,
166 | histogram.getTotalCount(),
167 | histogram.getMean() / 1E6,
168 | histogram.getMinValue() / 1E6,
169 | histogram.getMaxValue() / 1E6,
170 | histogram.getStdDeviation() / 1E6,
171 | histogram.getValueAtPercentile(0.5) / 1E6,
172 | histogram.getValueAtPercentile(0.75) / 1E6,
173 | histogram.getValueAtPercentile(0.98) / 1E6,
174 | histogram.getValueAtPercentile(0.99) / 1E6,
175 | histogram.getValueAtPercentile(0.999) / 1E6);
176 | }
177 |
178 | private ExecutorService getExecutorService() {
179 | if (stopLeakage) {
180 | // Return a single executor service.
181 | if (executorService == null) {
182 | synchronized (this) {
183 | if (executorService == null) {
184 | executorService = Executors.newFixedThreadPool(threads);
185 | }
186 | }
187 | }
188 | return executorService;
189 | } else {
190 | // Always to return a new executor service to leak threads.
191 | return Executors.newFixedThreadPool(threads);
192 | }
193 | }
194 |
195 | /**
196 | * Run parallel merge sort algorithm
197 | *
198 | * @param numbers The numbers to sort.
199 | */
200 | private void parallelMergeSort(int[] numbers) {
201 | parallelMergeSort(numbers, getExecutorService(), threads);
202 | }
203 |
204 | /**
205 | * This is a recursive method.
206 | *
207 | * @param numbers The numbers to sort.
208 | * @param executorService The {@link ExecutorService} to submit parallel tasks.
209 | * @param threadCount The number of threads to use
210 | */
211 | private void parallelMergeSort(int[] numbers, ExecutorService executorService, int threadCount) {
212 | if (threadCount <= 1) {
213 | mergeSort(numbers);
214 | } else if (numbers.length >= 2) {
215 | // split array in half
216 | int[] left = Arrays.copyOfRange(numbers, 0, numbers.length / 2);
217 | int[] right = Arrays.copyOfRange(numbers, numbers.length / 2, numbers.length);
218 | Runnable leftSorter = () -> parallelMergeSort(left, executorService, threadCount / 2);
219 | Runnable rightSorter = () -> parallelMergeSort(right, executorService, threadCount / 2);
220 | Future> leftResult = executorService.submit(leftSorter);
221 | Future> rightResult = executorService.submit(rightSorter);
222 | try {
223 | leftResult.get();
224 | rightResult.get();
225 | } catch (Exception e) {
226 | throw new RuntimeException("Unexpected error", e);
227 | }
228 | // merge them back together
229 | merge(left, right, numbers);
230 | }
231 | }
232 |
233 | /**
234 | * Arranges the elements of the given array into sorted order
235 | * using the "merge sort" algorithm, which splits the array in half,
236 | * recursively sorts the halves, then merges the sorted halves.
237 | * It is O(N log N) for all inputs.
238 | *
239 | * @param numbers The numbers to sort.
240 | */
241 | private void mergeSort(int[] numbers) {
242 | if (numbers.length >= 2) {
243 | // split array in half
244 | int[] left = Arrays.copyOfRange(numbers, 0, numbers.length / 2);
245 | int[] right = Arrays.copyOfRange(numbers, numbers.length / 2, numbers.length);
246 |
247 | // sort the halves
248 | mergeSort(left);
249 | mergeSort(right);
250 |
251 | // merge them back together
252 | merge(left, right, numbers);
253 | }
254 | }
255 |
256 | /**
257 | * Combines the contents of sorted left/right arrays into output array numbers.
258 | * Assumes that left.length + right.length == numbers.length.
259 | *
260 | * @param left The left array.
261 | * @param right The right array.
262 | * @param numbers The output array.
263 | */
264 | private void merge(int[] left, int[] right, int[] numbers) {
265 | int i1 = 0;
266 | int i2 = 0;
267 | for (int i = 0; i < numbers.length; i++) {
268 | if (i2 >= right.length || (i1 < left.length && left[i1] < right[i2])) {
269 | numbers[i] = left[i1];
270 | i1++;
271 | } else {
272 | numbers[i] = right[i2];
273 | i2++;
274 | }
275 | }
276 | }
277 |
278 | /**
279 | * Creates an array of the given length, fills it with random
280 | * non-negative integers, and returns it.
281 | *
282 | * @param length The length of the array.
283 | * @return An array of random numbers with given length.
284 | */
285 | private int[] createRandomArray(int length) {
286 | int[] numbers = new int[length];
287 | for (int i = 0; i < numbers.length; i++) {
288 | numbers[i] = random.nextInt(bound);
289 | }
290 | return numbers;
291 | }
292 |
293 | /**
294 | * Returns true if the given array is sorted in ascending order.
295 | *
296 | * @param numbers The number array.
297 | * @return {@code true} if the array is sorted in ascending order, otherwise {@code false}
298 | */
299 | private boolean isSorted(int[] numbers) {
300 | for (int i = 0; i < numbers.length - 1; i++) {
301 | if (numbers[i] > numbers[i + 1]) {
302 | return false;
303 | }
304 | }
305 | return true;
306 | }
307 |
308 | @Override
309 | public String toString() {
310 | return "ThreadLeakApplication{" +
311 | "threads=" + threads +
312 | ", length=" + length +
313 | ", runs=" + runs +
314 | ", bound=" + bound +
315 | ", delay=" + delay +
316 | ", period=" + period +
317 | ", stopLeakage=" + stopLeakage +
318 | ", exitTimeoutInSeconds=" + exitTimeoutInSeconds +
319 | '}';
320 | }
321 | }
322 |
--------------------------------------------------------------------------------
/threadleak/src/main/resources/META-INF/services/com.github.chrishantha.sample.base.SampleApplication:
--------------------------------------------------------------------------------
1 | com.github.chrishantha.sample.threadleak.ThreadLeakApplication
--------------------------------------------------------------------------------