In the java.util package, many classes are mutable, meaning their internal state can change after creation. If multiple threads share the same instance, changes made in one thread can unexpectedly impact others, leading to bugs. These problems drove the creation of immutable classes in the java.time package introduced in Java 8.
import java.util.Date; public class MutableDateExample { public static void main(String[] args) { Date sharedDate = new Date(); // Initial date Runnable task1 = () -> { sharedDate.setYear(2025 - 1900); // Mutate the date (Deprecated method) System.out.println("Task 1: " + sharedDate); }; Runnable task2 = () -> { sharedDate.setMonth(5); // Mutate the month System.out.println("Task 2: " + sharedDate); }; new Thread(task1).start(); new Thread(task2).start(); } }
Concurrency Issues: In the example above, both tasks modify the sharedDate object concurrently. This can lead to unpredictable results because Date is mutable and not thread-safe.
Data Integrity: Modifications in one part of the code can unexpectedly affect other parts where the same date object is used, leading to incorrect data or logic errors.
Mutable class: java.util.Date, java.util.Calendar, java.util.GregorianCalendar, java.text.SimpleDateFormat, java.util.TimeZone, java.util.Locale
The java.time API is designed to be safe and unchangeable. Its classes are immutable, meaning once you create an object, it can't be changed. To update a date or time, you create a new object with the updated value instead of changing the original one.
LocalDate initialDate = LocalDate.of(2024, 8, 21); // Initial date // Create a new date by adding 5 days LocalDate updatedDate = initialDate.plusDays(5); // Print the initial and updated dates System.out.println("Initial Date: " + initialDate); System.out.println("Updated Date: " + updatedDate); // Print the memory addresses of the initial and updated dates System.out.println("Initial Date Address: " + System.identityHashCode(initialDate)); System.out.println("Updated Date Address: " + System.identityHashCode(updatedDate)); // example output // Initial Date: 2024-08-21 // Updated Date: 2024-08-26 // Initial Date Address: 1555845260 // Updated Date Address: 1590550415
The above is the detailed content of Mutable & Immutable Java DateTime API. For more information, please follow other related articles on the PHP Chinese website!