Search code examples
javamultithreadingstaticthread-safetyfinal

Using final in method parameters in Java


As a user newly switching to Java, I have realized that in our project and some other Java projects, final keyword is commonly used and after reading several tutorials and SO threads e.g. Excessive use "final" keyword in Java, I think there is some examples that do not require final keyword. So, here are the points I am confused:

1. Is there any need to use final keyword in method parameters in classes and interfaces? Because

CompanyDTO findByUuid(final UUID uuid);

//or

@Override
public CompanyDTO findByUuid(final UUID uuid) {
    //...
}

2. As far as I know, it also good for thread safety, but I need to understand the basic idea on why it is used almost every possible places in Java. Normally it is used for the variables that will not be changed. So, could you please explain the idea of common usage?


Solution

    1. Using final modifier on method parameters doesn't make much sense since it adds visual clutter to the method declaration without buying you much. As far as you can make sure that you don't reassign values to those variables, you are good enough to go without final modifier on method parameters.
    2. Method parameters lie on the stack, and it is local to that particular thread as far as that thread doesn't publish it to some other thread. Since it is not shared between the other threads, no thread safety issue arises here. However, if the current thread publishes these arguments, then you are out of luck and the use of final modifier doesn't give you any thread safety guarantee.

    Here's one such a tasteful use of final modifier to write an immutable class which represents a point in our 2-dimensional space.

    class Point2D {
        private final int x;
        private final int y;
    
        Point2D(int x, int y) {
            this.x = x;
            this.y = y;
        }
    
        // Remainder omitted for brevity's sake !
    }
    

    Once this class instance is created, you can share it freely with other threads and you don't need to bother synchronizing access to it's state. So, immutable objects give you thread safety for free.

    You may read JLS § 17.5 for more details on semantics of final fields.