CodexBloom - Programming Q&A Platform

Java 17: Issues with Thread-Safe Singleton Implementation Using Enum

๐Ÿ‘€ Views: 4 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-08
java singleton thread-safety enum Java

I've looked through the documentation and I'm still confused about I'm encountering unexpected behavior when trying to implement a thread-safe singleton using an enum in Java 17. I have the following code: ```java public enum Singleton { INSTANCE; private String value; Singleton() { value = "Initial Value"; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } ``` When I try to modify the value concurrently from multiple threads, I expect the changes to be synchronized due to the singleton nature, but I am facing inconsistent results. Hereโ€™s how Iโ€™m modifying the value: ```java public class Main { public static void main(String[] args) throws InterruptedException { Runnable task = () -> { for (int i = 0; i < 10; i++) { Singleton.INSTANCE.setValue("Value " + i); System.out.println(Singleton.INSTANCE.getValue()); } }; Thread thread1 = new Thread(task); Thread thread2 = new Thread(task); thread1.start(); thread2.start(); thread1.join(); thread2.join(); } } ``` Iโ€™m seeing interleaved output, which suggests the enumโ€™s instance is not being accessed in a thread-safe manner. I assumed that using an enum would inherently provide the necessary thread-safety due to the JVM guarantees, but it seems that the mutable state within the singleton is causing issues. Iโ€™ve tried synchronizing the `setValue` method: ```java public synchronized void setValue(String value) { this.value = value; } ``` However, this approach introduces a bottleneck, and I'm concerned about performance. Is there a better pattern I can use to maintain both thread safety and performance while keeping the flexibility of mutable state? Is the use of an enum in this context appropriate, or should I consider a different approach? Any insights would be appreciated! How would you solve this? This is part of a larger web app I'm building. Thanks in advance!