DEV Community

ChelseaLiu0822
ChelseaLiu0822

Posted on

Shared model immutability

SimpleDateFormat is thread-unsafe, you can use DateTimeFormatter (immutable class, thread-safe) under multi-threading

Immutable design:

  • Classes and all properties in a class are final Modifying the property with final ensures that the property is read-only and cannot be modified. Modifying a class with final ensures that methods in the class cannot be overridden, preventing subclasses from inadvertently destroying immutability. -Protective copy: avoid sharing by creating copy objects Protective copy to ensure that the array contents will not be changed by other classes.

Flyweight pattern

Share data as much as possible
Since protective copy creates multiple objects and wastes resources, flyweight mode is usually used.
This pattern is often used in wrapper classes
The valueOf method of Long type will cache Long objects between -128 and 127. Objects will be reused within this range. New Long objects will be created only when the range is greater than this range.

final principle

Principle of setting final variables

Image description
Stateless is also thread-safe and is achieved by not setting member variables in the class.

Top comments (0)