Create rule S6810: Async methods should return void or Future (#3243)

This commit is contained in:
github-actions[bot] 2023-10-23 15:17:17 +02:00 committed by GitHub
parent 9aca4314df
commit a7522a3ca1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 73 additions and 0 deletions

View File

@ -0,0 +1,23 @@
{
"title": "Async methods should return void or Future",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-6810",
"sqKey": "S6810",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "unknown",
"code": {
"impacts": {
"RELIABILITY": "MEDIUM"
},
"attribute": "CONVENTIONAL"
}
}

View File

@ -0,0 +1,48 @@
== Why is this an issue?
The Spring framework provides the annotation `Async` to mark a method (or all methods of a type) as a candidate for asynchronous execution.
Asynchronous methods do not necessarily, by their nature, return the result of their calculation immediately.
Hence, it is unexpected and in clear breach of the `Async` contract for such methods to have a return type that is neither `void` nor a `Future` type.
== How to fix it
Use `void` as the return type if the method is not expected to return a result.
Otherwise, a `Future` should be returned, allowing the caller to retrieve the result once it is ready.
It is permitted to return more specific subtypes that inherit from `Future`.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
@Async
public String asyncMethod() {
...
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
@Async
public Future<String> asyncMethod() {
...
}
----
Alternatively, if the method does not need to return a result:
[source,java]
----
@Async
public void asyncMethod() {
...
}
----
== Resources
=== Documentation
* Spring Framework Documentation - https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Async.html[Annotation Interface Async]

View File

@ -0,0 +1,2 @@
{
}