google / error-prone

Catch common Java mistakes as compile-time errors
https://errorprone.info
Apache License 2.0
6.86k stars 744 forks source link

Method assumes exclusive ownership of any reference passed as this parameter #533

Open kevinb9n opened 7 years ago

kevinb9n commented 7 years ago

There are numerous library methods having the property that once a reference is passed as a parameter, it is wrong for anyone else to ever interact with that reference directly again.

Examples:

(will try to dig up a more complete list)

If we could annotate such parameters, it would (a) serve as useful documentation, and (b) allow Error Prone to enforce that any reference passed in "provably" isn't being retained anywhere.

One risk I see is that the heuristic could get complicated. For example, if the values were computed by a static library method, technically that library method could store the reference somewhere, but as humans we can recognize when that's a preposterous concern. We might have to think more about this recognition.

Annotation name is another mystery. @Surrender? @CallerSurrenders? @MustNotRetain?

The motivation to do this hinges largely on whether we would use it to create efficient "unsafe" versions of methods like ImmutableList.copyOf(), which could potentially be a big performance win, but it's possible we wouldn't be willing to do that anyway.

kevinb9n commented 7 years ago

Another interesting case is varargs methods. They would sometimes prefer to use the array passed in directly, which is almost always fine because the user never refers to the array. But if a user does pass an explicit array, that method might benefit from this kind of checking.