ZonedDateTime is part of the Java Date-Time API, and it represents a date-time with a time-zone in the ISO-8601 calendar system. One of the key features of ZonedDateTime is its immutability, which means that once an instance is created, it cannot be changed. This behavior makes ZonedDateTime safe to use in multithreaded code.
Since ZonedDateTime is immutable, you can share instances across multiple threads without worrying about thread-safety issues or data corruption. Each thread can safely read the ZonedDateTime instance without any locks or synchronization mechanisms. However, if you need to perform modifications, you will need to create new instances, as the original instance will remain unchanged.
Here's a simple example demonstrating the usage of ZonedDateTime in a multithreaded environment:
// Import necessary packages
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class ZonedDateTimeExample {
public static void main(String[] args) {
ZonedDateTime zonedDateTime = ZonedDateTime.now();
Runnable task = () -> {
// Each thread will read the same ZonedDateTime instance
String formattedDateTime = zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z"));
System.out.println("Current Date and Time : " + formattedDateTime);
};
// Create multiple threads
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
Thread thread3 = new Thread(task);
thread1.start();
thread2.start();
thread3.start();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?