I do not have a lot of experience in Java and I have not used java.util.Optional map function in production code. However, I need to use it for implementing a use case and the first thought which came to my mind, is this thread-safe ? As long as the mapping function in the argument is thread-safe, can we assume the overall operation will be thread safe ? How can I test this ?
I appreciate the help.
Thank you.
Optional.map
is as thread-safe as the function you pass in as the parameter. Essentially all it does is:
public <V> Optional<V> map(Function<? super T, ? extends V> fn) {
if (isPresent()) {
V value = fn.apply(get());
if (value != null) {
return Optional.of(value);
}
}
return Optional.absent();
}
Since Optional
is immutable (meaning that isPresent()
and get()
always return the same value, and the value returned by get()
will have been safely published), the only thing here that could possibly be thread-unsafe is the call fn.apply(get())
.
As long as the mapping function in the argument is thread-safe, can we assume the overall operation will be thread safe ? How can I test this ?
With great difficulty. You can't really write a test to prove that something is thread-safe, because you can't prove the reason you didn't observe thread-unsafety is because of the correctness of your code, or because your test simply didn't do anything that would exercise the thread-unsafety.
You can only do this by reasoning about the code with respect to the properties of the Java Memory Model.