当前位置:网站首页>Wrote a few small pieces of code, broke the system, and was blasted by the boss
Wrote a few small pieces of code, broke the system, and was blasted by the boss
2022-07-24 17:24:00 【Second brother learns Java】
Java The program is based on GC Of , At the beginning of startup , I applied for a sufficient amount of memory pool , Plus JIT And the real-time optimization of the compiler , It's no faster than using C++ Slow language writing .Java Language is both reflective and observable , Plus JFR This artifact , When a problem occurs, it is easier to find its root than binary files .
Recently in to see RCA(Root Cause Analysis) Things that are , Accidentally found out yCrash Such a thing . It's a few small pieces of problem code, which is very typical , We can take a little look at , Let's see Java Several common crash scenarios for applications .
1. Heap space overflow
OOM It's usually caused by a memory leak , Performance in GC In the Journal , In general, it's GC It's getting longer , And the effect of each recovery is very general .GC after , The actual usage of heap memory is on the rise .
The following code is an endless loop , Keep going to HashMap Richards data , because myMap Belong to GCRoots, Never released , So the end result is OOM.
import java.util.HashMap;
public class OOMDemo {
static HashMap<Object, Object> myMap = new HashMap<>();
public static void start() throws Exception {
while (true) {
myMap.put("key" + counter, "Large stringgggggggggggggggggggggggggggg"
+ "ggggggggggggggggggggggggggggggggggggggggggggggggggggg"
+ "ggggggggggggggggggggggggggggggggggggggggggggggggggggg"
+ "ggggggggggggggggggggggggggggggggggggggggggggggggggggg"
+ "ggggggggggggggggggggggggggggggggggggggggggggggggggggg"
+ "ggggggggggggggggggggggggggggggggggggggggggggggggggggg"
+ "ggggggggggggggggggggggggggggggggggggggggggggggggggggg"
+ "ggggggggggggggggggggggggggggggggggggggggggggggggggggg"
+ "ggggggggggggggggggggggggggggggggggggggggggggggggggggg"
+ "ggggggggggggggggggggggggggggggggggggggggggggggggggggg"
+ "ggggggggggggggggggggggggggggggggggggggggggggggggggggg"
+ "ggggggggggggggggggggggggggggggggggggggggggggggggggggg"
+ counter);
++counter;
}
}
}
2. Memory leak
Memory leaks and memory overflows are the same thing , The difference is its meaning .
Memory overflow may be due to excessive requests , Or the consequences of real business needs , The memory overflow is unknown 、 Beyond expectations OOM situation .
We can use the same code above to achieve this .
In reality , Memory leaks are usually very hidden , Need help Mat Wait for tools to find the root cause .jmap、pmap And so on are common tools .
such as , If you forget to rewrite the object hashCode and equals Method , There will be a memory leak .
//leak example : created by xjjdog 2022
import java.util.HashMap;
import java.util.Map;
public class HashMapLeakDemo {
public static class Key {
String title;
public Key(String title) {
this.title = title;
}
}
public static void main(String[] args) {
Map<Key, Integer> map = new HashMap<>();
map.put(new Key("1"), 1);
map.put(new Key("2"), 2);
map.put(new Key("3"), 2);
Integer integer = map.get(new Key("2"));
System.out.println(integer);
}
}
3.CPU soaring
Direct a dead cycle , You can put the CPU Dry to death .
public class CPUSpikeDemo {
public static void start() {
new CPUSpikerThread().start();
new CPUSpikerThread().start();
new CPUSpikerThread().start();
new CPUSpikerThread().start();
new CPUSpikerThread().start();
new CPUSpikerThread().start();
System.out.println("6 threads launched!");
}
}
public class CPUSpikerThread extends Thread {
@Override
public void run() {
while (true) {
// Just looping infinitely
}
}
}
To get the problem code, you can usually use the following method .
(1) Use top command , Found using CPU Most of a process , Record its pid. Use Shift + P Shortcut keys can be pressed CPU The usage rate of the .(2) Again using top command , Add -H Parameters , View the... Used in a process CPU The largest number of threads , Record the thread's ID.(3) Use printf function , Will be decimal tid Convert to hex .(4) Use jstack command , see Java Thread stack of process .(5) Use less Command to view the generated file , And find the hexadecimal conversion just now tid, Find the thread context where the problem occurred .
4. Thread leak
Thread resources are expensive . If you keep creating threads , System resources will soon be exhausted . The following code keeps creating threads , If there is more pressure to request at the same time , Most can kill the host .
public class ThreadLeakDemo {
public static void start() {
while (true) {
new ForeverThread().start();
}
}
}
public class ForeverThread extends Thread {
@Override
public void run() {
// Put the thread to sleep forever, so they don't die.
while (true) {
try {
// Sleeping for 10 minutes repeatedly
Thread.sleep(10 * 60 * 1000);
} catch (Exception e) {}
}
}
}
This is violence , This is similar to creating a thread for each request , Or the consequences of creating a thread pool are the same .xjjdog There are also two related thread leakage articles .
- Strongly opposed to the use of Spring Encapsulated multithreaded class !
- Fatal failure ! Blew up investors !
java.lang.OutOfMemoryError: unable to create new native thread
5. Deadlock
Deadlock codes generally do not occur , But once it happens, it's still very serious , Related businesses may not be able to run .
public class DeadLockDemo {
public static void start() {
new ThreadA().start();
new ThreadB().start();
}
}
public class ThreadA extends Thread {
@Override
public void run() {
CoolObject.method1();
}
}
public class ThreadB extends Thread {
@Override
public void run() {
HotObject.method2();
}
}
public class CoolObject {
public static synchronized void method1() {
try {
// Sleep for 10 seconds
Thread.sleep(10 * 1000);
} catch (Exception e) {}
HotObject.method2();
}
}
public class HotObject {
public static synchronized void method2() {
try {
// Sleep for 10 seconds
Thread.sleep(10 * 1000);
} catch (Exception e) {}
CoolObject.method1();
}
}
Deadlock is a serious situation ,jstack Will prompt with obvious information . Of course , About threads dump, There are also some online analysis tools available . such as fastthread, But you also need to understand the meaning of these situations .

6. Stack overflow
Stack overflow does not cause JVM Process death , harm “ Relatively small ”. The following is a simple code to simulate stack overflow , Just call recursively .
public class StackOverflowDemo {
public void start() {
start();
}
}
adopt -Xss Parameter can set the size of the virtual machine stack . For example, the following command is to set the stack size to 128K.
-Xss128K
If this happens frequently in your application , Try increasing this value . But it is usually caused by program errors , You'd better check your code .
7.Blocked Threads
BLOCKED Is a more serious thread state , When the processing time of the back-end service is very long , The requested thread will enter the waiting state . At this time through jstack To get the stack , You will find that the thread is blocked . It blocks the acquisition of locks (wating to lock)
public class BlockedAppDemo {
public static void start() {
for (int counter = 0; counter < 10; ++counter) {
// Launch 10 threads.
new AppThread().start();
}
}
}
public class AppThread extends Thread {
@Override
public void run() {
AppObject.getSomething();
}
}
public class AppObject {
public static synchronized void getSomething() {
while (true) {
try {
Thread.sleep(10 * 60 * 1000);
} catch (Exception e) {}
}
}
}
Once this happens frequently , It proves that your program is too slow . If CPU There is a surplus of resources , You can try to increase the number of threads requested , such as tomcat Is the maximum number of threads .
End
That's what it's all about Java Analysis of several small codes of common faults , Most of the faults can't escape these scenarios . Troubleshooting is usually very energy-consuming , And you have to have access to the cable . How to make some useful tools , Mask these complexities behind , That's what we want .
边栏推荐
- Reptiles and counter crawls: an endless battle
- 荣耀CEO赵明:单一厂商很难实现全场景产品覆盖
- 启发式合并(含一般式、树上启发式合并 例题)
- Atcoder beginer 202 e - count descendants (heuristic merge on heavy chain split tree for offline query)
- Separation and merging of channels
- 代码随想录笔记_链表_707设计链表
- UFW port forwarding
- Kernel development
- Axi protocol (3): handshake mechanism and implementation details of Axi architecture
- Zhao Ming, CEO of glory: it is difficult for a single manufacturer to achieve full scene product coverage
猜你喜欢
随机推荐
NATBypass 端口转发
Three.js (7): local texture refresh
滚动条调整亮度和对比度
Analyze the capabilities and scenarios of Apache pulsar, a cloud native message flow system
Opencv has its own color operation
Check the actual data growth of the database
[sequential logic circuit] - counter
QT QML virtual keyboard
通道的分离与合并
Axi protocol (1): introduction to AMBA bus, introduction to Axi concept and background, characteristics and functions of Axi protocol
hcip第三天
Still developing games with unity? Then you're out. Try unity to build an answer system
Topic 6 - message queue for client communication
Want to make sandbox games? Then you must not miss this plug-in (unity3d)
2022 牛客暑期多校 K - Link with Bracket Sequence I(线性dp)
Cann training camp learns the animation stylization and AOE ATC tuning of the second season of 2022 model series
Small end format and big end format (little endian & big endian)
【零基础】充分理解WebGL(八)
GDB online debugging of work notes
AI opportunities for operators: expand new tracks with large models








