当前位置:网站首页>Design and application of immutable classes
Design and application of immutable classes
2022-07-01 05:10:00 【People below two meters are mortals】
List of articles
1、 The problem of date conversion
@Slf4j
public class Test {
@SneakyThrows
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for (int i = 0; i < 10; i++) {
new Thread(() -> {
try {
log.info("{}", sdf.parse("1951-04-21"));
} catch (Exception e) {
log.info("{}", e);
}
}).start();
}
}
}
The above code is prone to the following errors , as a result of SimpleDateFormat Not thread safe , Is a mutable class , That is, its internal state is variable

I want to solve this problem , Of course, the conventional practice is to lock , But locking will inevitably lead to performance degradation
2、 The use of immutable classes
If you can guarantee the internal state of an object ( attribute ) Cannot be modified , So it's thread safe , Because there is no concurrent modification ! In fact, such objects are Java There are a lot of , For example, in Java 8 after , Provides a new date formatting class DateTimeFormatter , It is an immutable class , So it is a thread safe class
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
for (int i = 0; i < 10; i++) {
new Thread(() -> {
LocalDate date = dtf.parse("2022-02-11", LocalDate::from);
log.info("{}", date);
}).start();
}

3、 The design of immutable classes
We use String Class, for example , Explain the elements of immutable design , Observing the source code is not difficult to find , This kind 、 All properties in the class are final Of :
- Properties with final Modification ensures that the property is read-only , Do not modify
- Class with final Modification ensures that methods in this class cannot be overridden , Prevent subclasses from inadvertently destroying immutability
and , All the modification methods , Such as substring etc. , Its interior is also newly created String , And copy the original character array , This means of avoiding sharing by creating replica objects is called 【 Protective copy (defensive copy)】
边栏推荐
- Global and Chinese market of paper machine systems 2022-2028: Research Report on technology, participants, trends, market size and share
- [hardware ten treasures catalogue] - reprinted from "hardware 100000 whys" (under continuous update ~ ~)
- Receiving package install and uninstall events
- 工业导电滑环的应用
- 云原生存储解决方案Rook-Ceph与Rainbond结合的实践
- JS random verification code
- AssertionError assert I.ndim == 4 and I.shape[1] == 3
- 【暑期每日一题】洛谷 P2637 第一次,第二次,成交!
- 打印流与System.setout();
- FileOutPutStream
猜你喜欢

轻松上手Fluentd,结合 Rainbond 插件市场,日志收集更快捷

Copy baby prompt: material cannot be empty. How to solve it?

Unity drags and modifies scene camera parameters under the editor

0xc000007b应用程序无法正常启动解决方案(亲测有效)

el-form表单新增表单项动态校验;el-form校验动态表单v-if不生效;

提高企业产品交付效率系列(1)—— 企业应用一键安装和升级

複制寶貝提示材質不能為空,如何解决?
![[NLP Li Hongyi] notes](/img/8e/a51ca5eee638facd54270fb28d2fce.jpg)
[NLP Li Hongyi] notes

Data loading and preprocessing

Leetcode1497- check whether array pairs can be divided by K - array - hash table - count
随机推荐
解决:拖动xib控件到代码文件中,报错setValue:forUndefinedKey:this class is not key value coding-compliant for the key
Causes of short circuit of conductive slip ring and Countermeasures
Tcp/ip explanation (version 2) notes / 3 link layer / 3.2 Ethernet and IEEE 802 lan/man standards
智慧运维:基于 BIM 技术的可视化管理系统
【暑期每日一题】洛谷 P2026 求一次函数解析式
【暑期每日一题】洛谷 P1568 赛跑
Use of STM32 expansion board temperature sensor and temperature humidity sensor
How to use common datasets in pytorch
Global and Chinese market of mainboard 2022-2028: Research Report on technology, participants, trends, market size and share
【暑期每日一题】洛谷 P2637 第一次,第二次,成交!
And search: the suspects (find the number of people related to the nth person)
Basic skeleton of neural network nn Use of moudle
导电滑环使用的注意事项
Unit testing with mongodb
[daily question in summer] Luogu p5740 [deep foundation 7. Example 9] the best student
Pytoch (II) -- activation function, loss function and its gradient
Leetcode316- remove duplicate letters - stack - greedy - string
线程安全问题
RuntimeError: mean(): input dtype should be either floating point or complex dtypes. Got Long instead
【暑期每日一题】洛谷 P3742 umi的函数