当前位置:网站首页>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)】
边栏推荐
- How to use common datasets in pytorch
- AssertionError assert I.ndim == 4 and I.shape[1] == 3
- Principle, technology and implementation scheme of data consistency in distributed database
- [hardware ten treasures catalogue] - reprinted from "hardware 100000 whys" (under continuous update ~ ~)
- LeetCode522-最长特殊序列II-哈希表-字符串-双指针
- [daily question in summer] letter delivery by p1629 postman in Luogu (to be continued...)
- Oracle views the creation time of the tablespace in the database
- Global and Chinese market of mainboard 2022-2028: Research Report on technology, participants, trends, market size and share
- Pico neo3 handle grabs objects
- LevelDB源码分析之memtable
猜你喜欢
提高企业产品交付效率系列(1)—— 企业应用一键安装和升级
Detailed explanation of distributed global unique ID solution
Data loading and preprocessing
C read / write application configuration file app exe. Config and display it on the interface
Single page application
Use of dataloader
Daily question -leetcode1175- permutation of prime numbers - Mathematics
Vmware workstation network card settings and three common network modes
Spanner 论文小结
複制寶貝提示材質不能為空,如何解决?
随机推荐
Is there any good website or software for learning programming? [introduction to programming]?
Copier le matériel de conseils de bébé ne peut pas être vide, comment résoudre?
Solve the problem that the external chain file of Qiankun sub application cannot be obtained
Oracle views the creation time of the tablespace in the database
Solution: drag the Xib control to the code file, and an error setvalue:forundefined key:this class is not key value coding compliant for the key is reported
Global and Chinese market for instant messaging security and compliance solutions 2022-2028: Research Report on technology, participants, trends, market size and share
FileOutPutStream
Use of STM32 expansion board temperature sensor and temperature humidity sensor
How to meet the requirements of source code confidentiality and source code security management
云原生存储解决方案Rook-Ceph与Rainbond结合的实践
Several methods of creating thread classes
Use of dataloader
Global and Chinese market of 3D CAD 2022-2028: Research Report on technology, participants, trends, market size and share
提高企业产品交付效率系列(1)—— 企业应用一键安装和升级
Neural networks - use of maximum pooling
LevelDB源码分析之LRU Cache
Global and Chinese market of digital badge 2022-2028: Research Report on technology, participants, trends, market size and share
Some common commands of podman
【暑期每日一題】洛穀 P1568 賽跑
QDataStream的简单读写验证