java Basic Tutorial column introduces bugs caused by i.
Hello everyone, as someone who writes and fixes bugs on a daily basis, today I will bring you an accident that was just fixed a few days ago. I have to admit that there are always so many bugs wherever I am.
Cause
The story started a few days ago. There was an export function that was not very commonly used and was reported by users, no matter what the conditions were. , there is only one piece of data exported, but in fact there is a lot of data queried according to the conditions, and a lot of data is also queried on the page. (This problem has been fixed, so the Kibana logs at that time can no longer be found) So I put down my work and jumped in to look at this problem.
Analysis
From the description of the problem, it can only occur in the following situations:
- There is only one record queried based on the search conditions .
- Perform related business processing on the queried data, resulting in only one final result.
- After the logical processing of the file export component, there is only one result.
Digression
After writing this, I suddenly thought of a classic interview question, analysis of the cause of MQ message loss. Hahaha, in fact, it is roughly analyzed from several angles. (I will write an article about MQ when I have the opportunity)
Digression
So I will analyze them one by one:
- Find the SQL of the relevant business and the corresponding parameters, which can be obtained by query. There is more than one piece of data, so the first situation can be ruled out.
- The intermediate business involves relevant permissions, data sensitivity, etc. After releasing these, there is still only one piece of data.
- When the file export component receives the data, the printed log also shows only one entry, which means that there must be a problem with the logic of the related business.
Since this code is written in the entire method, it is difficult for Arthas to troubleshoot, so we have to set up the log step by step for troubleshooting. (So, if it is a large piece of logic, it is recommended to split it into duoge sub-methods. First of all, the idea will be clear when writing, and there will be a modular concept. As for method reuse, I won’t mention it more. Basic operations ; Second, once a problem occurs, it will be easier to troubleshoot, speaking from experience).
Finally positioned inside a for loop.
Code
Without further ado, let’s look at the code directly. As we all know, I have always been a person who protects the company's code, so I have to simulate it for everyone here. Judging from the problem, the exported object record is empty
import?com.google.common.collect.Lists;import?java.util.List;public?class?Test?{????public?static?void?main(String[]?args)?{????????//?獲取Customer數(shù)據(jù),這里就簡(jiǎn)單模擬 ????????List<Customer>?customerList?=?Lists.newArrayList(new?Customer("Java"),?new?Customer("Showyool"),?new?Customer("Soga"));????????int?index?=?0; ????????String[][]?exportData?=?new?String[customerList.size()][2];????????for?(Customer?customer?:?customerList)?{ ????????????exportData[index][0]?=?String.valueOf(index); ????????????exportData[index][1]?=?customer.getName(); ????????????index?=?index++; ????????} ????????System.out.println(JSON.toJSONString(exportData)); ????} }class?Customer?{????public?Customer(String?name)?{????????this.name?=?name; ????}????private?String?name;????public?String?getName()?{????????return?name; ????}????public?void?setName(String?name)?{????????this.name?=?name; ????} }復(fù)制代碼
This code seems to be nothing, it is to convert the Customer collection into a two-dimensional array of strings. But the output result shows: This is in line with what we said. There are multiple queries, but only one is output.
Looking carefully, we can find that the output data is always the last one. That is to say, every time the Customer collection is traversed, the latter overwrites the former. That is to say, the lower part of this index The scale has never changed and is always 0.
Modeling
It seems that our self-increment does have some problems, so let’s simply write a model
public?class?Test2?{????public?static?void?main(String[]?args)?{????????int?index?=?3; ????????index?=?index++; ????????System.out.println(index); ????} ???? }復(fù)制代碼
We simplify the above business logic into For such a model, the result is unsurprisingly 3.
Explanation
Then let’s execute javap and see how the JVM bytecode is interpreted:
javap?-c?Test2 Compiled?from?"Test2.java"public?class?com.showyool.blog_4.Test2?{??public?com.showyool.blog_4.Test2(); ????Code:???????0:?aload_0???????1:?invokespecial?#1??????????????????//?Method?java/lang/Object."<init>":()V ???????4:?return ??public?static?void?main(java.lang.String[]); ????Code:???????0:?iconst_3???????1:?istore_1???????2:?iload_1???????3:?iinc??????????1,?1 ???????6:?istore_1???????7:?getstatic?????#2??????????????????//?Field?java/lang/System.out:Ljava/io/PrintStream; ??????10:?iload_1??????11:?invokevirtual?#3??????????????????//?Method?java/io/PrintStream.println:(I)V ??????14:?return}復(fù)制代碼
Here I will briefly talk about the JVM bytecode instructions here (later I will write an article in detail when I have the opportunity)
First of all, we need to know that there are two concepts here, the operand stack and the local variable table. These two are some data structures in the stack frame in the virtual machine stack. , as shown in the figure:
We can simply understand that the function of the operand stack is to store data and calculate data in the stack, while the local variable table is to store variables some information.
Then let’s take a look at the above instructions:
0: iconst_3 (first push the constant 3 onto the stack)
1: istore_1 (出棧操作,將值賦給第一個(gè)參數(shù),也就是將3賦值給index)
2: iload_1 ?(將第一個(gè)參數(shù)的值壓入棧,也就是將3入棧,此時(shí)棧頂?shù)闹禐?)
3: iinc 1, 1 (將第一個(gè)參數(shù)的值進(jìn)行自增操作,那么此時(shí)index的值是4)
6: istore_1 (出棧操作,將值賦給第一個(gè)參數(shù),也就是將3賦值給index)
也就是說index這個(gè)參數(shù)的值是經(jīng)歷了index->3->4->3,所以這樣一輪操作之后,index又回到了一開始賦值的值。
延伸一下
這樣一來,我們發(fā)現(xiàn),問題其實(shí)出在最后一步,在進(jìn)行運(yùn)算之后,又將原先棧中記錄的值重新賦給變量,覆蓋掉了 如果我們這樣寫:
public?class?Test2?{????public?static?void?main(String[]?args)?{????????int?index?=?3; ????????index++; ????????System.out.println(index); ????} } Compiled?from?"Test2.java"public?class?com.showyool.blog_4.Test2?{??public?com.showyool.blog_4.Test2(); ????Code:???????0:?aload_0???????1:?invokespecial?#1??????????????????//?Method?java/lang/Object."<init>":()V ???????4:?return ??public?static?void?main(java.lang.String[]); ????Code:???????0:?iconst_3???????1:?istore_1???????2:?iinc??????????1,?1 ???????5:?getstatic?????#2??????????????????//?Field?java/lang/System.out:Ljava/io/PrintStream; ???????8:?iload_1???????9:?invokevirtual?#3??????????????????//?Method?java/io/PrintStream.println:(I)V ??????12:?return}復(fù)制代碼
可以發(fā)現(xiàn),這里就沒有最后一步的istore_1,那么在iinc之后,index的值就變成我們預(yù)想的4。
還有一種情況,我們來看看:
public?class?Test2?{????public?static?void?main(String[]?args)?{????????int?index?=?3; ????????index?=?index?+?2; ????????System.out.println(index); ????} } Compiled?from?"Test2.java"public?class?com.showyool.blog_4.Test2?{??public?com.showyool.blog_4.Test2(); ????Code:???????0:?aload_0???????1:?invokespecial?#1??????????????????//?Method?java/lang/Object."<init>":()V ???????4:?return ??public?static?void?main(java.lang.String[]); ????Code:???????0:?iconst_3???????1:?istore_1???????2:?iload_1???????3:?iconst_2???????4:?iadd???????5:?istore_1???????6:?getstatic?????#2??????????????????//?Field?java/lang/System.out:Ljava/io/PrintStream; ???????9:?iload_1??????10:?invokevirtual?#3??????????????????//?Method?java/io/PrintStream.println:(I)V ??????13:?return}復(fù)制代碼
0: iconst_3 (先將常量3壓入棧)
1: istore_1 (出棧操作,將值賦給第一個(gè)參數(shù),也就是將3賦值給index)
2: iload_1 ?(將第一個(gè)參數(shù)的值壓入棧,也就是將3入棧,此時(shí)棧頂?shù)闹禐?)
3: iconst_2 (將常量2壓入棧, 此時(shí)棧頂?shù)闹禐?,2在3之上)
4: iadd (將棧頂?shù)膬蓚€(gè)數(shù)進(jìn)行相加,并將結(jié)果壓入棧。2+3=5,此時(shí)棧頂?shù)闹禐?)
5: istore_1 (出棧操作,將值賦給第一個(gè)參數(shù),也就是將5賦值給index)
看到這里各位觀眾老爺肯定會(huì)有這么一個(gè)疑惑,為什么這里的iadd加法操作之后,會(huì)影響棧里面的數(shù)據(jù),而先前說的iinc不是在棧里面操作?好的吧,我們可以看看JVM虛擬機(jī)規(guī)范當(dāng)中,它是這么描述的:
指令iinc對(duì)給定的局部變量做自增操作,這條指令是少數(shù)幾個(gè)執(zhí)行過程中完全不修改操作數(shù)棧的指令。它接收兩個(gè)操作數(shù): 第1個(gè)局部變量表的位置,第2個(gè)位累加數(shù)。比如常見的i++,就會(huì)產(chǎn)生這條指令
看到這里,我們知道,對(duì)于一般的加法操作之后復(fù)制沒啥問題,但是使用i++之后,那么此時(shí)棧頂?shù)臄?shù)還是之前的舊值,如果此刻進(jìn)行賦值就會(huì)回到原來的舊值,因?yàn)樗]有修改棧里面的數(shù)據(jù)。所以先前那個(gè)bug,只需要進(jìn)行自增不賦值就可以修復(fù)了。
Finally
Thank you all for seeing this. The above is my entire process of dealing with this bug. Although this is just a small bug, this small bug is still worth learning and thinking about. I will continue to share the bugs and knowledge points I found in the future. If my article is helpful to you, I also hope you guys
Related free learning recommendations:
The above is the detailed content of Solve a bug caused by i++. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa
