Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The static method java.lang.ThreadLocal.withInitial is added On line 99 #301

Merged
merged 8 commits into from
Nov 20, 2021
7 changes: 6 additions & 1 deletion src/classes/java/lang/ThreadLocal.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import java.lang.ref.WeakReference;
import java.util.Objects;
import java.util.function.Supplier;
import java.sql.Date;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove these two unused imports.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes are done

import java.text.SimpleDateFormat;

/**
* model of java.lang.ThreadLocal, which avoids global shared objects
Expand Down Expand Up @@ -96,7 +98,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
Original file line number Diff line number Diff line change
@@ -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);
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a newline character (line break) at the end of the last line.