简体   繁体   中英

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)?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM