Skip to content

Commit

Permalink
Fix #292: Add static method java.lang.ThreadLocal.withInitial (#301)
Browse files Browse the repository at this point in the history
* 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)
  • Loading branch information
gaurangkudale committed Nov 20, 2021
1 parent 07fd626 commit f8b4549
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/classes/java/lang/ThreadLocal.java
Expand Up @@ -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
Expand Down Expand Up @@ -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<E> extends ThreadLocal<E> {

public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
return new SuppliedThreadLocal<>(supplier);
}

// we need to preserve the modifiers since this might introduce races (supplier could be shared)
private final Supplier<? extends E> sup;

Expand Down
21 changes: 21 additions & 0 deletions src/tests/ThreadLocalTest/App.java
@@ -0,0 +1,21 @@
import java.sql.Date;
import java.text.SimpleDateFormat;

class threadSafeFormatter{
public static ThreadLocal<SimpleDateFormat> 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);
}
}

0 comments on commit f8b4549

Please sign in to comment.