alibaba / alibaba/fastjson2

[BUG]core/src/main/java/com/alibaba/fastjson2/support/csv/CSVReader.java的rowCount方法未能正确关闭资源,可能导致应用程序崩溃

Open
#2,112 1 comment 0 reactions 0 assignees View on GitHub
bug
Dominant language
Java
Stars
4.4k
Forks
613
Avg merge
1d 22h
Merged PRs (30d)
6

Description

### 问题描述
core/src/main/java/com/alibaba/fastjson2/support/csv/CSVReader.java的rowCount方法未能正确关闭资源,可能导致应用程序崩溃
实现Closeable接口或接口AutoCloseable的类在使用后需要关闭。此外,close调用必须在finally块中进行,否则异常可能会阻止调用的进行。当类实现AutoCloseable时,资源应该使用“try-with-resources”模式创建,并将自动关闭。
能正确关闭资源将导致资源泄漏,这可能首先导致应用程序崩溃,然后可能导致机器崩溃。
### 环境信息

- OS信息: Windows 10 11th Gen Intel(R) Core(TM) i5-11400H @ 2.70GHz 2.69 GHz 16.0 GB
- JDK信息: 1.8.0_261
- 版本信息:Fastjson2 2.0.39

### 期待的正确结果
public static int rowCount(String str, Feature... features) throws IOException {
try (CSVReader state = new CSVReaderUTF8(features)) {
state.rowCount(str, str.length());
return state.rowCount();
} catch (Exception e) {
// 处理异常
e.printStackTrace();
throw e;
}
// try-with-resources会自动关闭资源
}

public static int rowCount(byte[] bytes, Feature... features) {
try (CSVReaderUTF8 state = new CSVReaderUTF8(features)) {
state.rowCount(bytes, bytes.length);
return state.rowCount();
} catch (Exception e) {
// 处理异常
e.printStackTrace();
throw e;
}
// try-with-resources会自动关闭资源
}

public static int rowCount(char[] chars, Feature... features) {
try (CSVReaderUTF16 state = new CSVReaderUTF16(features)) {
state.rowCount(chars, chars.length);
return state.rowCount();
} catch (Exception e) {
// 处理异常
e.printStackTrace();
throw e;
}
// try-with-resources会自动关闭资源
}

public static int rowCount(InputStream in) throws IOException {
if (in == null) {
throw new IllegalArgumentException("InputStream cannot be null");
}

try (CSVReaderUTF8 state = new CSVReaderUTF8()) {
byte[] bytes = new byte[SIZE_512K];
while (true) {
int cnt = in.read(bytes);
if (cnt == -1) {
break;
}
state.rowCount(bytes, cnt);
}
return state.rowCount();
} catch (Exception e) {
// 处理异常
e.printStackTrace();
throw e;
}
}

#### 附加信息
![1](https://github.com/alibaba/fastjson2/assets/151609086/6f07bcbd-fa5e-4b3e-adcc-775288b87372)
![2](https://github.com/alibaba/fastjson2/assets/151609086/8fcf6093-3e74-44c2-afa5-c5562406bf6c)

Contributor guide

Open the contributing guide

Research direction

Start in core/src/main/java/com/alibaba/fastjson2/support/csv/CSVReader.java and inspect the rowCount overloads for String, byte[], char[], and InputStream. Trace how each creates and releases its CSVReader state, then verify the affected paths with the repository’s existing CSV tests. Done means row counting still returns the expected count and reader resources are closed when processing succeeds or throws.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
data
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.