当前位置:网站首页>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)】
边栏推荐
- Actual combat: gateway api-2022.2.13
- Oracle views the creation time of the tablespace in the database
- Spanner 论文小结
- Pytoch (I) -- basic grammar
- AcWing 886. Finding combinatorial number II (pretreatment factorial)
- Technology sharing | broadcast function design in integrated dispatching
- 积分商城游戏能够给商家带来什么?怎么搭建积分商城?
- [daily question in summer] Luogu p7222 [rc-04] informatics competition
- Global and Chinese market of digital badge 2022-2028: Research Report on technology, participants, trends, market size and share
- Use of STM32 expansion board temperature sensor and temperature humidity sensor
猜你喜欢

在Rainbond中一键部署高可用 EMQX 集群

Oracle views the creation time of the tablespace in the database

Distributed - summary list

How to use common datasets in pytorch

LevelDB源码分析之LRU Cache

Actual combat: gateway api-2022.2.13

Application of industrial conductive slip ring

RuntimeError: “max_pool2d“ not implemented for ‘Long‘

How to hide browser network IP address and modify IP internet access?

Unity drags and modifies scene camera parameters under the editor
随机推荐
1076 Forwards on Weibo
如何选择导电滑环材料
Global and Chinese market for instant messaging security and compliance solutions 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese markets of superconductor 2022-2028: Research Report on technology, participants, trends, market size and share
Leetcode316- remove duplicate letters - stack - greedy - string
【暑期每日一题】洛谷 P3742 umi的函数
[daily question in summer] first time, second time, deal!
Copier le matériel de conseils de bébé ne peut pas être vide, comment résoudre?
[hard ten treasures] - 1 [basic knowledge] classification of power supply
Unit testing with mongodb
Data loading and preprocessing
LevelDB源码分析之LRU Cache
[daily question in summer] Luogu p1568 race
Buffer stream and transform stream
LeetCode1497-检查数组对是否可以被 k 整除-数组-哈希表-计数
Application of industrial conductive slip ring
C read / write application configuration file app exe. Config and display it on the interface
Manually implement a simple stack
Global and Chinese markets for business weather forecasting 2022-2028: Research Report on technology, participants, trends, market size and share
AcWing 886. Finding combinatorial number II (pretreatment factorial)