java.util 패키지에서는 많은 클래스가 변경 가능합니다. 즉, 생성 후 내부 상태가 변경될 수 있습니다. 여러 스레드가 동일한 인스턴스를 공유하는 경우 한 스레드의 변경 사항이 예기치 않게 다른 스레드에 영향을 미쳐 버그가 발생할 수 있습니다. 이러한 문제로 인해 Java 8에 도입된 java.time 패키지에 불변 클래스가 생성되었습니다.
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(); } }
동시성 문제: 위의 예에서 두 작업 모두 sharedDate 객체를 동시에 수정합니다. Date는 변경 가능하고 스레드로부터 안전하지 않기 때문에 예측할 수 없는 결과가 발생할 수 있습니다.
데이터 무결성: 코드의 한 부분을 수정하면 동일한 날짜 개체가 사용되는 다른 부분에 예상치 못한 영향을 미쳐 잘못된 데이터 또는 논리 오류가 발생할 수 있습니다.
변경 가능한 클래스: java.util.Date, java.util.Calendar, java.util.GregorianCalendar, java.text.SimpleDateFormat, java.util.TimeZone, java.util.Locale
java.time API는 안전하고 변경할 수 없도록 설계되었습니다. 해당 클래스는 변경할 수 없습니다. 즉, 일단 객체를 생성하면 변경할 수 없습니다. 날짜나 시간을 업데이트하려면 원래 값을 변경하는 대신 업데이트된 값으로 새 개체를 만듭니다.
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
위 내용은 변경 가능 및 불변 Java DateTime API의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!