Skip to content

[java] LawOfDemeter: False positive with Thread and ThreadLocalRandom  #2180

Closed
@linusjf

Description

@linusjf

#2160 (comment)
Affects PMD Version:
6.20.0
Rule:
LawOfDemeter.
Description:
Thread.currentThread() and ThreadLocalRandom().current() calls must be exempted from the method chaining and local object creation flagging by this rule. These calls and objects returned are thread-specific and for all practical purposes are pseudo-static properties.
You can add ProcessHandle.current() as another API call to be treated similarly.

Code Sample demonstrating the issue:

package pmdtests;

import java.util.concurrent.ThreadLocalRandom;
import static java.lang.System.out;

public class TaskLocalRandom implements Runnable {

 
  @Override
  public void run() {
    StringBuilder sb = new StringBuilder(40);
    sb.append(Thread.currentThread().getName()).append(" with priority ")
      .append(Thread.currentThread().getPriority())
      .append(": %d %n");
    String str = sb.toString();
    for (int i = 0; i < 10; i++)
      out.printf(
          str, 
         ThreadLocalRandom.current().nextInt(10) );
  }
}

Running PMD through: [CLI | Ant | Maven | Gradle | Designer | Other]

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions