Java String 不变性与 String 对象实例

标签 java string

在 Java 中 strings are special .

Since string literals with the same contents share storage in the common pool, Java's String is designed to be immutable. That is, once a String is constructed, its contents cannot be modified. Otherwise, the other String references sharing the same storage location will be affected by the change, which can be unpredictable and therefore is undesirable.

如果我在字符串上同步怎么办?我会锁定共享相同内容的所有 String 实例吗?

例如:我有一个多线程类,它从数据文件中读取和写入。每天有 1 个文件,我想同步对同一个文件的读取和写入,以防止不可预测的行为。我可以简单地同步文件名(字符串)吗?

最佳答案

您可以实习该字符串,但这对于下一个必须维护代码的人来说有点不透明。我建议您创建一个 File 对象或一个名为 fileLock 的单独对象(例如)以更清楚地表示意图。

关于Java String 不变性与 String 对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49708477/

相关文章:

java - 如何在war中更新jar文件

java - JNA 按名称从进程获取模块

javascript - jQuery 获取所有属性作为字符串变体

javascript - 为什么近几年 JS 文件中更常用单引号?

java - 在每个第 n 个字符处拆分一个字符串

java - 终止 CycAPI Cyc 连接的首选方法是什么?

java - Spring MVC 和 Thymeleaf Button 禁用更新

java - 我应该将我的 Angular 文件放在同一个 JEE 项目中吗?

javascript - 将匹配字符串中最后一次出现的点的正则表达式

c# - 获取两个字符串的公共(public)前缀