From f8b4549b2b6820c32fe61de26bd9ccfe36994e4d Mon Sep 17 00:00:00 2001 From: Gaurang Kudale <64984006+gaurangkudale@users.noreply.github.com> Date: Sat, 20 Nov 2021 19:05:54 +0530 Subject: [PATCH] Fix #292: Add static method java.lang.ThreadLocal.withInitial (#301) * The static method java.lang.ThreadLocal.withInitial is added On line 99 * Added ThreadLocalTest to "src/tests" * Imports are removed and added a newline character (line break) --- src/classes/java/lang/ThreadLocal.java | 6 +++++- src/tests/ThreadLocalTest/App.java | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 src/tests/ThreadLocalTest/App.java diff --git a/src/classes/java/lang/ThreadLocal.java b/src/classes/java/lang/ThreadLocal.java index 43ea225f..9d5cca72 100644 --- a/src/classes/java/lang/ThreadLocal.java +++ b/src/classes/java/lang/ThreadLocal.java @@ -22,6 +22,7 @@ import java.util.Objects; import java.util.function.Supplier; + /** * model of java.lang.ThreadLocal, which avoids global shared objects * that can otherwise considerably contribute to the state space @@ -96,7 +97,10 @@ public void remove(){ // Java 8 provides this as an internal type to be used from lib classes // ?? why is this not done with overridden initialValue() within the concrete ThreadLocal class static final class SuppliedThreadLocal extends ThreadLocal { - + public static ThreadLocal withInitial(Supplier supplier) { + return new SuppliedThreadLocal<>(supplier); + } + // we need to preserve the modifiers since this might introduce races (supplier could be shared) private final Supplier sup; diff --git a/src/tests/ThreadLocalTest/App.java b/src/tests/ThreadLocalTest/App.java new file mode 100644 index 00000000..7889549b --- /dev/null +++ b/src/tests/ThreadLocalTest/App.java @@ -0,0 +1,21 @@ +import java.sql.Date; +import java.text.SimpleDateFormat; + +class threadSafeFormatter{ + public static ThreadLocal df = ThreadLocal.withInitial(() + -> new SimpleDateFormat("yyyy-MM-dd")); +} + +public class App { + public static void main(String[] args) throws Exception { + threadSafeFormatter tf = new threadSafeFormatter(); + Thread t1 = new Thread(); + t1.start(); + } + + public static String birthDate(int userId){ + Date birthdDate = new Date(userId); + final SimpleDateFormat df = threadSafeFormatter.df.get(); + return df.format(birthdDate); + } +}