Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why need final def in poll() method of LinkedList in Java

Tags:

java

/**
 * Retrieves and removes the head (first element) of this list.
 *
 * @return the head of this list, or {@code null} if this list is empty
 * @since 1.5
 */
public E poll() {
    final Node<E> f = first; //why final here? <<-------- ******* --------
    return (f == null) ? null : unlinkFirst(f);
}

Hi there, I'm reading the source code of JDK 1.7. In above code snippet in LinkedList.java, I cannot understand why need 'final' in poll() method. Why not :

public E poll() {
    return (first == null) ? null : unlinkFirst(first);
}

Can you share the insight of the implementation? Thanks.

like image 780
windkiosk Avatar asked Feb 11 '23 07:02

windkiosk


2 Answers

Most of the methods in LinkedList use the final declaration on local variables.

LinkedList JDK 1.7 Source

This is likely related to the concept behind Using "final" modifier whenever applicable in java.

Adding final to all things which should not change simply narrows down the possibilities that you (or the next programmer, working on your code) will misinterpret or misuse the thought process which resulted in your code. At least it should ring some bells when they now want to change your previously immutable thing.

Technically, at the cost of 6 letters, you guarantee that something you don't ever expect to change will never change.

Does your proposed code work? Yes. I don't see any scenarios where it wouldn't. It is programmatically valid.

However, the use of final throughout the code supports sanity testing, and understandably, for all the util stuff that holds pretty much all of the things we do in Java together, it'd be nice to know that everything is working as intended.

Note: If there is a security issue that I have not seen, however, I would be interested to know about that, in a separate answer.

like image 105
Compass Avatar answered Feb 13 '23 19:02

Compass


Martin Buchholz answered this on the concurrency-interest list in a related question:

We in jsr166-land consider our software important enough to make optimizations we don't recommend to regular java programmers. Copying final fields to locals generates smaller bytecode and might help the jit produce better code (and with current hotspot, still does).

Using final on locals has no performance advantage, but it does have some software engineering advantages. We tend to use it for locals with the same name as a field, e.g.

final Foo foo = this.foo;

like image 33
jmehrens Avatar answered Feb 13 '23 20:02

jmehrens