Sonar Rule for detecting Concurrency Problem due to usage of instance variables in Singletons

Hi,
we have had an issue in our web application where a developer had a singleton, and inadvertently used instance variables that were shared by several threads that accessed the singleton at the same time.

A very simple example of such a class would be the following:

import jakarta.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class GreetingService {

    private String firstName;
    private String lastName;

    /**
     * Generates a greeting for the given names.
     */
    public String generateGreeting(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;

        return "Hello " + this.firstName + " " + this.lastName + "!";
    }
}

Obviously, as soon as two users access this class at the same time, their data will get mixed up.

Unfortunately, SonarQube did not detect this error. Is there any way that I can make SonarQube detect this or similar errors?

I did not find any matching Sonar Rule for this. I must admit that I have never before tried implementing a custom rule, so I thought I’d rather check if there is a simpler solution.
We are you using

SonarQube Server Enterprise Edition v2025.1.1 (104738)

Hi Stefan,

If I understand it correctly, you would like to have a rule that requires that all public methods should be marked synchronized, if the object is @ApplicationScoped. Is this correct?

I could not find a matching rule either. If you would like to learn about writing custom rules, please take a look at sonar-java/docs/CUSTOM_RULES_101.md at master · SonarSource/sonar-java · GitHub

Hi Tomasz,
yes this is basically correct, allthough @ApplicationScoped might not be the only annotation that is relevant. Others might be @Singleton, @Component, @Service, @Repository… then again, for some of these, the default scope might be changed by an @Scope annotation. So in total, it’s probably not trivial to detect if a class is indeed being used as a singleton. So implementing a custom rule would probably be a big effort.
I wondered if this is not a rule that would be useful for all of the Sonar community, so wouldn’t it make sense for it to be integrated into Sonar itself? It would be a larger one-time effort for Sonar, but giving huge benefits to its customers.

Thanks for the additional context. I’ve added this to our backlog so it doesn’t get lost: SONARJAVA-5700. We may be able to discuss it internally the next time we tackle rules for enterprise applications.