As davmac already stated, MAP_A_TO_B()
is thread-safe because it always returns a new Function<A,B>
object regardless of the state of the program. Likewise, this Function<A,B>
object is thread-safe because it always performs the same logic: The only types which can be used in a switch statement are primitive wrapper types, String
and Enum
-- the first two are immutable and thus thread-safe and the last one is thread-safe because two different objects of the same Enum
subtype cannot be equivalent (e.g. Fruit.APPLE
and Fruit.PEAR
will never be equivalent even if they have mutable states and happen to be in equivalent states --- such as if they had a non-final field name
which was set to the same value).
However, instances of B
must be assumed not to be thread-safe since we don't have any information about them in your example: Unless it is defined as otherwise, assume that code is not thread-safe. Furthermore, even if a type's current implementation is thread-safe, if the type itself is not defined as such, this implementation may change to be non-thread-safe in the future and break code which depends on it being thread-safe.
Lastly, to be a pedant, it's better to define a "last-resort" switch case using the default
case:
public B apply(A) {
switch (A) {
case 1:
return B1;
case 2:
return B2;
default:
return B0;
}
}