Home > Java > javaTutorial > body text

Mutable & Immutable Java DateTime API

WBOY
Release: 2024-08-21 22:38:02
Original
445 people have browsed it

Mutable & Immutable Java DateTime API

Mutable DateTime Classes

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();
    }
}
Copy after login

Issues with Mutable Date/Time Classes

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

Immutable DateTime

java.time Package (Introduced in Java 8)

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.

  • Key Classes
    • LocalDate, LocalTime, LocalDateTime: Represent date and time without time zone information.
    • ZonedDateTime, OffsetDateTime, OffsetTime: Represent date and time with time zone or offset information.
    • Instant: Represents a specific moment in time (UTC).
    • Duration, Period: Represent time-based and date-based amounts of time.
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
Copy after login

Summary:

  • Mutable Classes (java.util.Date, java.util.Calendar): Prone to issues such as concurrency problems, unintended side effects, and historical bugs. Suitable only for legacy code or specific scenarios where immutability is not a concern.
  • Immutable Classes (java.time): Provide thread safety, predictable behavior, and overall better design. They should be preferred for new codebases and when working with modern Java applications.

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!