Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining java.util.function.Function as static final

In my code we have to convert euros into euro cents: taken a BigDecimal as input we have to multiply it by 100.

We need to apply this conversion a lot of times, so we decided to use an UnaryOperator from java.util.function:

private static final UnaryOperator<BigDecimal> CONVERT_EURO_TO_CENTS =
        input -> input.multiply(BigDecimal.valueOf(100)).setScale(0, RoundingMode.DOWN);

Then we used the CONVERT_EURO_TO_CENTS as follows:

[.....]

    CONVERT_EURO_TO_CENT.apply(<aBigDecimal>)

[.....]

Could be dangerous declaring the UnaryOperator as a constant (static final), avoiding data inconsistency in a multi-threaded environment (thread safety)?

like image 862
DistribuzioneGaussiana Avatar asked Feb 28 '26 06:02

DistribuzioneGaussiana


1 Answers

No, this isn’t dangerous.

If you make a mutable object and put it in a static field then different threads can change its state and cause trouble.

Here though the static final field holds a reference to a lambda, and nothing there is mutable. It doesn’t have any state that multiple threads can tamper with. Each operation on BigDecimal is thread-safe, BigDecimal is immutable. Even if BigDecimal wasn’t threadsafe other threads wouldn’t have access to the argument passed into the lambda.

Btw if you implement the lambda with local variables, that’s still thread-safe, the only state is confined to the stack frame executing the method.

Consider if you’re going to put this lambda in a variable and use it in different places you might as well use a static method. You’re not gaining anything making this a lambda. If you need to pass it as an argument you can still do that using a method reference.

like image 194
Nathan Hughes Avatar answered Mar 02 '26 21:03

Nathan Hughes