rspec/rules/S4065/java/rule.adoc

48 lines
1016 B
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Java 8 introduced ``++ThreadLocal.withInitial++`` which is a simpler alternative to creating an anonymous inner class to initialise a ``++ThreadLocal++`` instance.
This rule raises an issue when a ``++ThreadLocal++`` anonymous inner class can be replaced by a call to ``++ThreadLocal.withInitial++``.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
ThreadLocal<List<String>> myThreadLocal =
new ThreadLocal<List<String>>() { // Noncompliant
@Override
protected List<String> initialValue() {
return new ArrayList<String>();
}
};
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
ThreadLocal<List<String>> myThreadLocal = ThreadLocal.withInitial(ArrayList::new);
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Replace this anonymous class with a call to "ThreadLocal.withInitial".
=== Highlighting
ThreadLocal instance creation
endif::env-github,rspecator-view[]