java:S1854 False Positive

  • Operating system: Windows 10
  • SonarLint plugin version:
  • Programming language you’re coding in: Java
  • Is connected mode used: No

I am getting an accusation of S1854: Useless Assignment to variable for the following code:

01. short timeOuts = 0;
03. while (!Thread.currentThread().isInterrupted()) {
04.   try {
05.     Message rawMessage = (Message) socketIn.readObject();
06.     timeOuts = 0;
07.     // ...
08.   } catch (SocketTimeoutException ignored) {
09.     timeOuts++;
10.     if (timeOuts > 5)
11.       throw new IOException();
12.   }
13. }

Irrelevant parts of the code were omitted for clarity. It initializes a counter of socket time outs to 0 (L01), and then counts the number of time outs that happen in a row (L08-12). If a message arrives after one or more time outs, the counter is reset to 0 (L06). S1854 is accused on L06, but were that assignment to be removed, the time out counter would never be reset upon receiving a message.

Hello Marcelo!

Thank you for your report. Indeed, it sounds as though it could be a false positive.

Unfortunately, I am having trouble reproducing the issue with only the code provided. Perhaps the rule behaves strangely due to some code hidden by the // ... in your example. Or maybe I introduced some logic that makes it disappear while adapting the code to make it compile.

Could you provide a snippet that compiles stand-alone and raises the FP nevertheless?

I have an example for failure in this Rule:
Does not work:


Hey @renoth

Thanks for following up with a reproducer – can you please provide formatted snippets of code rather than screenshots?