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