The following issues were found

guava/src/com/google/common/collect/AbstractMapBasedMultiset.java
36 issues
This class has too many methods, consider refactoring it.
Design

Line: 52

              @GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
abstract class AbstractMapBasedMultiset<E extends @Nullable Object> extends AbstractMultiset<E>
    implements Serializable {
  // TODO(lowasser): consider overhauling this back to Map<E, Integer>
  private transient Map<E, Count> backingMap;

  /*
   * Cache the size for efficiency. Using a long lets us avoid the need for

            

Reported by PMD.

Field size has the same name as a method
Error

Line: 61

                 * overflow checking and ensures that size() will function correctly even if
   * the multiset had once been larger than Integer.MAX_VALUE.
   */
  private transient long size;

  /** Standard constructor. */
  protected AbstractMapBasedMultiset(Map<E, Count> backingMap) {
    checkArgument(backingMap.isEmpty());
    this.backingMap = backingMap;

            

Reported by PMD.

Overriding method merely calls super
Design

Line: 84

                 * was retrieved.
   */
  @Override
  public Set<Multiset.Entry<E>> entrySet() {
    return super.entrySet();
  }

  @Override
  Iterator<E> elementIterator() {

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 90

              
  @Override
  Iterator<E> elementIterator() {
    final Iterator<Map.Entry<E, Count>> backingEntries = backingMap.entrySet().iterator();
    return new Iterator<E>() {
      @CheckForNull Map.Entry<E, Count> toRemove;

      @Override
      public boolean hasNext() {

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 104

                    public E next() {
        final Map.Entry<E, Count> mapEntry = backingEntries.next();
        toRemove = mapEntry;
        return mapEntry.getKey();
      }

      @Override
      public void remove() {
        checkState(toRemove != null, "no calls to next() since the last call to remove()");

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 110

                    @Override
      public void remove() {
        checkState(toRemove != null, "no calls to next() since the last call to remove()");
        size -= toRemove.getValue().getAndSet(0);
        backingEntries.remove();
        toRemove = null;
      }
    };
  }

            

Reported by PMD.

Assigning an Object to null is a code smell. Consider refactoring.
Error

Line: 112

                      checkState(toRemove != null, "no calls to next() since the last call to remove()");
        size -= toRemove.getValue().getAndSet(0);
        backingEntries.remove();
        toRemove = null;
      }
    };
  }

  @Override

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 119

              
  @Override
  Iterator<Entry<E>> entryIterator() {
    final Iterator<Map.Entry<E, Count>> backingEntries = backingMap.entrySet().iterator();
    return new Iterator<Multiset.Entry<E>>() {
      @CheckForNull Map.Entry<E, Count> toRemove;

      @Override
      public boolean hasNext() {

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 142

                        @Override
          public int getCount() {
            Count count = mapEntry.getValue();
            if (count == null || count.get() == 0) {
              Count frequency = backingMap.get(getElement());
              if (frequency != null) {
                return frequency.get();
              }
            }

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 145

                          if (count == null || count.get() == 0) {
              Count frequency = backingMap.get(getElement());
              if (frequency != null) {
                return frequency.get();
              }
            }
            return (count == null) ? 0 : count.get();
          }
        };

            

Reported by PMD.

guava-tests/test/com/google/common/reflect/SubtypeTester.java
36 issues
Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 81

                  boolean suppressGetSupertype() default false;
  }

  private Method method = null;

  /** Call this in a {@link TestSubtype} public method asserting subtype relationship. */
  final <T> T isSubtype(T sub) {
    Type returnType = method.getGenericReturnType();
    Type paramType = getOnlyParameterType();

            

Reported by PMD.

Avoid using redundant field initializer for 'method'
Performance

Line: 81

                  boolean suppressGetSupertype() default false;
  }

  private Method method = null;

  /** Call this in a {@link TestSubtype} public method asserting subtype relationship. */
  final <T> T isSubtype(T sub) {
    Type returnType = method.getGenericReturnType();
    Type paramType = getOnlyParameterType();

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 88

                  Type returnType = method.getGenericReturnType();
    Type paramType = getOnlyParameterType();
    TestSubtype spec = method.getAnnotation(TestSubtype.class);
    assertWithMessage("%s is subtype of %s", paramType, returnType)
        .that(TypeToken.of(paramType).isSubtypeOf(returnType))
        .isTrue();
    assertWithMessage("%s is supertype of %s", returnType, paramType)
        .that(TypeToken.of(returnType).isSupertypeOf(paramType))
        .isTrue();

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 88

                  Type returnType = method.getGenericReturnType();
    Type paramType = getOnlyParameterType();
    TestSubtype spec = method.getAnnotation(TestSubtype.class);
    assertWithMessage("%s is subtype of %s", paramType, returnType)
        .that(TypeToken.of(paramType).isSubtypeOf(returnType))
        .isTrue();
    assertWithMessage("%s is supertype of %s", returnType, paramType)
        .that(TypeToken.of(returnType).isSupertypeOf(paramType))
        .isTrue();

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 89

                  Type paramType = getOnlyParameterType();
    TestSubtype spec = method.getAnnotation(TestSubtype.class);
    assertWithMessage("%s is subtype of %s", paramType, returnType)
        .that(TypeToken.of(paramType).isSubtypeOf(returnType))
        .isTrue();
    assertWithMessage("%s is supertype of %s", returnType, paramType)
        .that(TypeToken.of(returnType).isSupertypeOf(paramType))
        .isTrue();
    if (!spec.suppressGetSubtype()) {

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 91

                  assertWithMessage("%s is subtype of %s", paramType, returnType)
        .that(TypeToken.of(paramType).isSubtypeOf(returnType))
        .isTrue();
    assertWithMessage("%s is supertype of %s", returnType, paramType)
        .that(TypeToken.of(returnType).isSupertypeOf(paramType))
        .isTrue();
    if (!spec.suppressGetSubtype()) {
      assertThat(getSubtype(returnType, TypeToken.of(paramType).getRawType())).isEqualTo(paramType);
    }

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 91

                  assertWithMessage("%s is subtype of %s", paramType, returnType)
        .that(TypeToken.of(paramType).isSubtypeOf(returnType))
        .isTrue();
    assertWithMessage("%s is supertype of %s", returnType, paramType)
        .that(TypeToken.of(returnType).isSupertypeOf(paramType))
        .isTrue();
    if (!spec.suppressGetSubtype()) {
      assertThat(getSubtype(returnType, TypeToken.of(paramType).getRawType())).isEqualTo(paramType);
    }

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 92

                      .that(TypeToken.of(paramType).isSubtypeOf(returnType))
        .isTrue();
    assertWithMessage("%s is supertype of %s", returnType, paramType)
        .that(TypeToken.of(returnType).isSupertypeOf(paramType))
        .isTrue();
    if (!spec.suppressGetSubtype()) {
      assertThat(getSubtype(returnType, TypeToken.of(paramType).getRawType())).isEqualTo(paramType);
    }
    if (!spec.suppressGetSupertype()) {

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 94

                  assertWithMessage("%s is supertype of %s", returnType, paramType)
        .that(TypeToken.of(returnType).isSupertypeOf(paramType))
        .isTrue();
    if (!spec.suppressGetSubtype()) {
      assertThat(getSubtype(returnType, TypeToken.of(paramType).getRawType())).isEqualTo(paramType);
    }
    if (!spec.suppressGetSupertype()) {
      assertThat(getSupertype(paramType, TypeToken.of(returnType).getRawType()))
          .isEqualTo(returnType);

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 95

                      .that(TypeToken.of(returnType).isSupertypeOf(paramType))
        .isTrue();
    if (!spec.suppressGetSubtype()) {
      assertThat(getSubtype(returnType, TypeToken.of(paramType).getRawType())).isEqualTo(paramType);
    }
    if (!spec.suppressGetSupertype()) {
      assertThat(getSupertype(paramType, TypeToken.of(returnType).getRawType()))
          .isEqualTo(returnType);
    }

            

Reported by PMD.

guava/src/com/google/common/util/concurrent/ServiceManager.java
36 issues
Logger calls should be surrounded by log level guards.
Design

Line: 280

                      // service or listener). Our contract says it is safe to call this method if
        // all services were NEW when it was called, and this has already been verified above, so we
        // don't propagate the exception.
        logger.log(Level.WARNING, "Unable to start Service " + service, e);
      }
    }
    return this;
  }


            

Reported by PMD.

Logger calls should be surrounded by log level guards.
Design

Line: 848

                       */
        log &= from != State.STARTING;
        if (log) {
          logger.log(
              Level.SEVERE,
              "Service " + service + " has failed in the " + from + " state.",
              failure);
        }
        state.transitionService(service, from, FAILED);

            

Reported by PMD.

A high number of imports can indicate a high degree of coupling within an object.
Design

Line: 15

               * the License.
 */

package com.google.common.util.concurrent;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Predicates.equalTo;

            

Reported by PMD.

This class has too many methods, consider refactoring it.
Design

Line: 125

               */
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ServiceManager implements ServiceManagerBridge {
  private static final Logger logger = Logger.getLogger(ServiceManager.class.getName());
  private static final ListenerCallQueue.Event<Listener> HEALTHY_EVENT =
      new ListenerCallQueue.Event<Listener>() {
        @Override
        public void call(Listener listener) {

            

Reported by PMD.

This abstract class does not have any abstract methods
Design

Line: 161

                 * @author Luke Sandberg
   * @since 15.0 (present as an interface in 14.0)
   */
  public abstract static class Listener {
    /**
     * Called when the service initially becomes healthy.
     *
     * <p>This will be called at most once after all the services have entered the {@linkplain
     * State#RUNNING running} state. If any services fail during start up or {@linkplain

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 193

                 * ServiceManager} constructor without having to close over the partially constructed {@link
   * ServiceManager} instance (i.e. avoid leaking a pointer to {@code this}).
   */
  private final ServiceManagerState state;

  private final ImmutableList<Service> services;

  /**
   * Constructs a new instance for managing the given services.

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 195

                 */
  private final ServiceManagerState state;

  private final ImmutableList<Service> services;

  /**
   * Constructs a new instance for managing the given services.
   *
   * @param services The services to manage

            

Reported by PMD.

Avoid instantiating new objects inside loops
Performance

Line: 219

                  this.services = copy;
    WeakReference<ServiceManagerState> stateReference = new WeakReference<>(state);
    for (Service service : copy) {
      service.addListener(new ServiceListener(service, stateReference), directExecutor());
      // We check the state after adding the listener as a way to ensure that our listener was added
      // to a NEW service.
      checkArgument(service.state() == NEW, "Can only manage NEW services, %s", service);
    }
    // We have installed all of our listeners and after this point any state transition should be

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 434

              
  @Override
  public String toString() {
    return MoreObjects.toStringHelper(ServiceManager.class)
        .add("services", Collections2.filter(services, not(instanceOf(NoOpService.class))))
        .toString();
  }

  /**

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 434

              
  @Override
  public String toString() {
    return MoreObjects.toStringHelper(ServiceManager.class)
        .add("services", Collections2.filter(services, not(instanceOf(NoOpService.class))))
        .toString();
  }

  /**

            

Reported by PMD.

guava/src/com/google/common/graph/AbstractValueGraph.java
35 issues
The class 'AbstractValueGraph' has a Modified Cyclomatic Complexity of 3 (Highest = 13).
Design

Line: 43

               */
@Beta
@ElementTypesAreNonnullByDefault
public abstract class AbstractValueGraph<N, V> extends AbstractBaseGraph<N>
    implements ValueGraph<N, V> {

  @Override
  public Graph<N> asGraph() {
    return new AbstractGraph<N>() {

            

Reported by PMD.

The class 'AbstractValueGraph' has a Standard Cyclomatic Complexity of 3 (Highest = 13).
Design

Line: 43

               */
@Beta
@ElementTypesAreNonnullByDefault
public abstract class AbstractValueGraph<N, V> extends AbstractBaseGraph<N>
    implements ValueGraph<N, V> {

  @Override
  public Graph<N> asGraph() {
    return new AbstractGraph<N>() {

            

Reported by PMD.

The method 'asGraph' has a Modified Cyclomatic Complexity of 13.
Design

Line: 47

                  implements ValueGraph<N, V> {

  @Override
  public Graph<N> asGraph() {
    return new AbstractGraph<N>() {
      @Override
      public Set<N> nodes() {
        return AbstractValueGraph.this.nodes();
      }

            

Reported by PMD.

The method 'asGraph' has a Standard Cyclomatic Complexity of 13.
Design

Line: 47

                  implements ValueGraph<N, V> {

  @Override
  public Graph<N> asGraph() {
    return new AbstractGraph<N>() {
      @Override
      public Set<N> nodes() {
        return AbstractValueGraph.this.nodes();
      }

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 51

                  return new AbstractGraph<N>() {
      @Override
      public Set<N> nodes() {
        return AbstractValueGraph.this.nodes();
      }

      @Override
      public Set<EndpointPair<N>> edges() {
        return AbstractValueGraph.this.edges();

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 51

                  return new AbstractGraph<N>() {
      @Override
      public Set<N> nodes() {
        return AbstractValueGraph.this.nodes();
      }

      @Override
      public Set<EndpointPair<N>> edges() {
        return AbstractValueGraph.this.edges();

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 56

              
      @Override
      public Set<EndpointPair<N>> edges() {
        return AbstractValueGraph.this.edges();
      }

      @Override
      public boolean isDirected() {
        return AbstractValueGraph.this.isDirected();

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 56

              
      @Override
      public Set<EndpointPair<N>> edges() {
        return AbstractValueGraph.this.edges();
      }

      @Override
      public boolean isDirected() {
        return AbstractValueGraph.this.isDirected();

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 61

              
      @Override
      public boolean isDirected() {
        return AbstractValueGraph.this.isDirected();
      }

      @Override
      public boolean allowsSelfLoops() {
        return AbstractValueGraph.this.allowsSelfLoops();

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 61

              
      @Override
      public boolean isDirected() {
        return AbstractValueGraph.this.isDirected();
      }

      @Override
      public boolean allowsSelfLoops() {
        return AbstractValueGraph.this.allowsSelfLoops();

            

Reported by PMD.

guava-tests/test/com/google/common/util/concurrent/ListeningScheduledExecutorServiceTest.java
35 issues
Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 32

              /** Tests for default methods of the interface. */
public class ListeningScheduledExecutorServiceTest extends TestCase {

  private Runnable recordedCommand;
  private long recordedDelay;
  private long recordedInterval;
  private TimeUnit recordedTimeUnit;

  private final ListeningScheduledExecutorService executorService = new FakeExecutorService();

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 33

              public class ListeningScheduledExecutorServiceTest extends TestCase {

  private Runnable recordedCommand;
  private long recordedDelay;
  private long recordedInterval;
  private TimeUnit recordedTimeUnit;

  private final ListeningScheduledExecutorService executorService = new FakeExecutorService();


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 34

              
  private Runnable recordedCommand;
  private long recordedDelay;
  private long recordedInterval;
  private TimeUnit recordedTimeUnit;

  private final ListeningScheduledExecutorService executorService = new FakeExecutorService();

  public void testScheduleRunnable() throws Exception {

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 35

                private Runnable recordedCommand;
  private long recordedDelay;
  private long recordedInterval;
  private TimeUnit recordedTimeUnit;

  private final ListeningScheduledExecutorService executorService = new FakeExecutorService();

  public void testScheduleRunnable() throws Exception {
    Runnable command = () -> {};

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 37

                private long recordedInterval;
  private TimeUnit recordedTimeUnit;

  private final ListeningScheduledExecutorService executorService = new FakeExecutorService();

  public void testScheduleRunnable() throws Exception {
    Runnable command = () -> {};

    ListenableScheduledFuture<?> future = executorService.schedule(command, Duration.ofSeconds(12));

            

Reported by PMD.

Unit tests should not contain more than 1 assert(s).
Design

Line: 39

              
  private final ListeningScheduledExecutorService executorService = new FakeExecutorService();

  public void testScheduleRunnable() throws Exception {
    Runnable command = () -> {};

    ListenableScheduledFuture<?> future = executorService.schedule(command, Duration.ofSeconds(12));

    assertThat(future.get()).isEqualTo("schedule");

            

Reported by PMD.

JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 39

              
  private final ListeningScheduledExecutorService executorService = new FakeExecutorService();

  public void testScheduleRunnable() throws Exception {
    Runnable command = () -> {};

    ListenableScheduledFuture<?> future = executorService.schedule(command, Duration.ofSeconds(12));

    assertThat(future.get()).isEqualTo("schedule");

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 44

              
    ListenableScheduledFuture<?> future = executorService.schedule(command, Duration.ofSeconds(12));

    assertThat(future.get()).isEqualTo("schedule");
    assertThat(recordedCommand).isSameInstanceAs(command);
    assertThat(recordedTimeUnit).isEqualTo(TimeUnit.NANOSECONDS);
    assertThat(Duration.ofNanos(recordedDelay)).isEqualTo(Duration.ofSeconds(12));
  }


            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 44

              
    ListenableScheduledFuture<?> future = executorService.schedule(command, Duration.ofSeconds(12));

    assertThat(future.get()).isEqualTo("schedule");
    assertThat(recordedCommand).isSameInstanceAs(command);
    assertThat(recordedTimeUnit).isEqualTo(TimeUnit.NANOSECONDS);
    assertThat(Duration.ofNanos(recordedDelay)).isEqualTo(Duration.ofSeconds(12));
  }


            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 45

                  ListenableScheduledFuture<?> future = executorService.schedule(command, Duration.ofSeconds(12));

    assertThat(future.get()).isEqualTo("schedule");
    assertThat(recordedCommand).isSameInstanceAs(command);
    assertThat(recordedTimeUnit).isEqualTo(TimeUnit.NANOSECONDS);
    assertThat(Duration.ofNanos(recordedDelay)).isEqualTo(Duration.ofSeconds(12));
  }

  public void testScheduleCallable() throws Exception {

            

Reported by PMD.

guava/src/com/google/common/math/Quantiles.java
35 issues
Avoid reassigning parameters such as 'to'
Design

Line: 530

                 * ({@code required}, {@code to}] are greater than or equal to that value. Therefore, the value at
   * {@code required} is the value which would appear at that index in the sorted dataset.
   */
  private static void selectInPlace(int required, double[] array, int from, int to) {
    // If we are looking for the least element in the range, we can just do a linear search for it.
    // (We will hit this whenever we are doing quantile interpolation: our first selection finds
    // the lower value, our second one finds the upper value by looking for the next least element.)
    if (required == from) {
      int min = from;

            

Reported by PMD.

Avoid reassigning parameters such as 'from'
Design

Line: 530

                 * ({@code required}, {@code to}] are greater than or equal to that value. Therefore, the value at
   * {@code required} is the value which would appear at that index in the sorted dataset.
   */
  private static void selectInPlace(int required, double[] array, int from, int to) {
    // If we are looking for the least element in the range, we can just do a linear search for it.
    // (We will hit this whenever we are doing quantile interpolation: our first selection finds
    // the lower value, our second one finds the upper value by looking for the next least element.)
    if (required == from) {
      int min = from;

            

Reported by PMD.

All methods are static. Consider using a utility class instead. Alternatively, you could add a private constructor or make the class abstract to silence this warning.
Design

Line: 132

              @Beta
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Quantiles {

  /** Specifies the computation of a median (i.e. the 1st 2-quantile). */
  public static ScaleAndIndex median() {
    return scale(2).index(1);
  }

            

Reported by PMD.

This class has too many methods, consider refactoring it.
Design

Line: 132

              @Beta
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Quantiles {

  /** Specifies the computation of a median (i.e. the 1st 2-quantile). */
  public static ScaleAndIndex median() {
    return scale(2).index(1);
  }

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 136

              
  /** Specifies the computation of a median (i.e. the 1st 2-quantile). */
  public static ScaleAndIndex median() {
    return scale(2).index(1);
  }

  /** Specifies the computation of quartiles (i.e. 4-quantiles). */
  public static Scale quartiles() {
    return scale(4);

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 167

                 */
  public static final class Scale {

    private final int scale;

    private Scale(int scale) {
      checkArgument(scale > 0, "Quantile scale must be positive");
      this.scale = scale;
    }

            

Reported by PMD.

It is somewhat confusing to have a field name matching the declaring class name
Error

Line: 167

                 */
  public static final class Scale {

    private final int scale;

    private Scale(int scale) {
      checkArgument(scale > 0, "Quantile scale must be positive");
      this.scale = scale;
    }

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 218

                 */
  public static final class ScaleAndIndex {

    private final int scale;
    private final int index;

    private ScaleAndIndex(int scale, int index) {
      checkIndex(index, scale);
      this.scale = scale;

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 219

                public static final class ScaleAndIndex {

    private final int scale;
    private final int index;

    private ScaleAndIndex(int scale, int index) {
      checkIndex(index, scale);
      this.scale = scale;
      this.index = index;

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 317

                 */
  public static final class ScaleAndIndexes {

    private final int scale;
    private final int[] indexes;

    private ScaleAndIndexes(int scale, int[] indexes) {
      for (int index : indexes) {
        checkIndex(index, scale);

            

Reported by PMD.

guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java
35 issues
Avoid instantiating new objects inside loops
Performance

Line: 315

                  ArrayList<LockGraphNode> nodes = Lists.newArrayListWithCapacity(numKeys);
    // Create a LockGraphNode for each enum value.
    for (E key : keys) {
      LockGraphNode node = new LockGraphNode(getLockName(key));
      nodes.add(node);
      map.put(key, node);
    }
    // Pre-populate all allowedPriorLocks with nodes of smaller ordinal.
    for (int i = 1; i < numKeys; i++) {

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 321

                  }
    // Pre-populate all allowedPriorLocks with nodes of smaller ordinal.
    for (int i = 1; i < numKeys; i++) {
      nodes.get(i).checkAcquiredLocks(Policies.THROW, nodes.subList(0, i));
    }
    // Pre-populate all disallowedPriorLocks with nodes of larger ordinal.
    for (int i = 0; i < numKeys - 1; i++) {
      nodes.get(i).checkAcquiredLocks(Policies.DISABLED, nodes.subList(i + 1, numKeys));
    }

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 325

                  }
    // Pre-populate all disallowedPriorLocks with nodes of larger ordinal.
    for (int i = 0; i < numKeys - 1; i++) {
      nodes.get(i).checkAcquiredLocks(Policies.DISABLED, nodes.subList(i + 1, numKeys));
    }
    return Collections.unmodifiableMap(map);
  }

  /**

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 335

                 * used in exception and warning output.
   */
  private static String getLockName(Enum<?> rank) {
    return rank.getDeclaringClass().getSimpleName() + "." + rank.name();
  }

  /**
   * A {@code CycleDetectingLockFactory.WithExplicitOrdering} provides the additional enforcement of
   * an application-specified ordering of lock acquisitions. The application defines the allowed

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 401

                public static final class WithExplicitOrdering<E extends Enum<E>>
      extends CycleDetectingLockFactory {

    private final Map<E, LockGraphNode> lockGraphNodes;

    @VisibleForTesting
    WithExplicitOrdering(Policy policy, Map<E, LockGraphNode> lockGraphNodes) {
      super(policy);
      this.lockGraphNodes = lockGraphNodes;

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 457

              
  private static final Logger logger = Logger.getLogger(CycleDetectingLockFactory.class.getName());

  final Policy policy;

  private CycleDetectingLockFactory(Policy policy) {
    this.policy = checkNotNull(policy);
  }


            

Reported by PMD.

Classes implementing Serializable should set a serialVersionUID
Error

Line: 490

                 *   at com...MyClass.someMethodThatAcquiresLockB(MyClass.java:123)
   * </pre>
   */
  private static class ExampleStackTrace extends IllegalStateException {

    static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0];

    static final ImmutableSet<String> EXCLUDED_CLASS_NAMES =
        ImmutableSet.of(

            

Reported by PMD.

Too many control variables in the for statement
Design

Line: 503

                  ExampleStackTrace(LockGraphNode node1, LockGraphNode node2) {
      super(node1.getLockName() + " -> " + node2.getLockName());
      StackTraceElement[] origStackTrace = getStackTrace();
      for (int i = 0, n = origStackTrace.length; i < n; i++) {
        if (WithExplicitOrdering.class.getName().equals(origStackTrace[i].getClassName())) {
          // For pre-populated disallowedPriorLocks edges, omit the stack trace.
          setStackTrace(EMPTY_STACK_TRACE);
          break;
        }

            

Reported by PMD.

Classes implementing Serializable should set a serialVersionUID
Error

Line: 538

                 * @since 13.0
   */
  @Beta
  public static final class PotentialDeadlockException extends ExampleStackTrace {

    private final ExampleStackTrace conflictingStackTrace;

    private PotentialDeadlockException(
        LockGraphNode node1, LockGraphNode node2, ExampleStackTrace conflictingStackTrace) {

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 561

                  public String getMessage() {
      // requireNonNull is safe because ExampleStackTrace sets a non-null message.
      StringBuilder message = new StringBuilder(requireNonNull(super.getMessage()));
      for (Throwable t = conflictingStackTrace; t != null; t = t.getCause()) {
        message.append(", ").append(t.getMessage());
      }
      return message.toString();
    }
  }

            

Reported by PMD.

android/guava/src/com/google/common/math/Quantiles.java
35 issues
Avoid reassigning parameters such as 'to'
Design

Line: 530

                 * ({@code required}, {@code to}] are greater than or equal to that value. Therefore, the value at
   * {@code required} is the value which would appear at that index in the sorted dataset.
   */
  private static void selectInPlace(int required, double[] array, int from, int to) {
    // If we are looking for the least element in the range, we can just do a linear search for it.
    // (We will hit this whenever we are doing quantile interpolation: our first selection finds
    // the lower value, our second one finds the upper value by looking for the next least element.)
    if (required == from) {
      int min = from;

            

Reported by PMD.

Avoid reassigning parameters such as 'from'
Design

Line: 530

                 * ({@code required}, {@code to}] are greater than or equal to that value. Therefore, the value at
   * {@code required} is the value which would appear at that index in the sorted dataset.
   */
  private static void selectInPlace(int required, double[] array, int from, int to) {
    // If we are looking for the least element in the range, we can just do a linear search for it.
    // (We will hit this whenever we are doing quantile interpolation: our first selection finds
    // the lower value, our second one finds the upper value by looking for the next least element.)
    if (required == from) {
      int min = from;

            

Reported by PMD.

All methods are static. Consider using a utility class instead. Alternatively, you could add a private constructor or make the class abstract to silence this warning.
Design

Line: 132

              @Beta
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Quantiles {

  /** Specifies the computation of a median (i.e. the 1st 2-quantile). */
  public static ScaleAndIndex median() {
    return scale(2).index(1);
  }

            

Reported by PMD.

This class has too many methods, consider refactoring it.
Design

Line: 132

              @Beta
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Quantiles {

  /** Specifies the computation of a median (i.e. the 1st 2-quantile). */
  public static ScaleAndIndex median() {
    return scale(2).index(1);
  }

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 136

              
  /** Specifies the computation of a median (i.e. the 1st 2-quantile). */
  public static ScaleAndIndex median() {
    return scale(2).index(1);
  }

  /** Specifies the computation of quartiles (i.e. 4-quantiles). */
  public static Scale quartiles() {
    return scale(4);

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 167

                 */
  public static final class Scale {

    private final int scale;

    private Scale(int scale) {
      checkArgument(scale > 0, "Quantile scale must be positive");
      this.scale = scale;
    }

            

Reported by PMD.

It is somewhat confusing to have a field name matching the declaring class name
Error

Line: 167

                 */
  public static final class Scale {

    private final int scale;

    private Scale(int scale) {
      checkArgument(scale > 0, "Quantile scale must be positive");
      this.scale = scale;
    }

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 218

                 */
  public static final class ScaleAndIndex {

    private final int scale;
    private final int index;

    private ScaleAndIndex(int scale, int index) {
      checkIndex(index, scale);
      this.scale = scale;

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 219

                public static final class ScaleAndIndex {

    private final int scale;
    private final int index;

    private ScaleAndIndex(int scale, int index) {
      checkIndex(index, scale);
      this.scale = scale;
      this.index = index;

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 317

                 */
  public static final class ScaleAndIndexes {

    private final int scale;
    private final int[] indexes;

    private ScaleAndIndexes(int scale, int[] indexes) {
      for (int index : indexes) {
        checkIndex(index, scale);

            

Reported by PMD.

android/guava/src/com/google/common/collect/ImmutableSet.java
35 issues
Avoid reassigning parameters such as 'setSize'
Design

Line: 217

                 * can hold setSize elements with the desired load factor. Always returns at least setSize + 2.
   */
  @VisibleForTesting
  static int chooseTableSize(int setSize) {
    setSize = Math.max(setSize, 2);
    // Correct the size for open addressing to match desired load factor.
    if (setSize < CUTOFF) {
      // Round up to the next highest power of 2.
      int tableSize = Integer.highestOneBit(setSize - 1) << 1;

            

Reported by PMD.

Possible God Class (WMC=48, ATFD=11, TCC=0.000%)
Design

Line: 51

              @GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
@ElementTypesAreNonnullByDefault
public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements Set<E> {
  /**
   * Returns the empty immutable set. Preferred over {@link Collections#emptySet} for code
   * consistency, and because the return type conveys the immutability guarantee.
   *
   * <p><b>Performance note:</b> the instance returned is a singleton.

            

Reported by PMD.

This class has too many methods, consider refactoring it.
Design

Line: 51

              @GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
@ElementTypesAreNonnullByDefault
public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements Set<E> {
  /**
   * Returns the empty immutable set. Preferred over {@link Collections#emptySet} for code
   * consistency, and because the return type conveys the immutability guarantee.
   *
   * <p><b>Performance note:</b> the instance returned is a singleton.

            

Reported by PMD.

The class 'ImmutableSet' has a Standard Cyclomatic Complexity of 2 (Highest = 10).
Design

Line: 51

              @GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
@ElementTypesAreNonnullByDefault
public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements Set<E> {
  /**
   * Returns the empty immutable set. Preferred over {@link Collections#emptySet} for code
   * consistency, and because the return type conveys the immutability guarantee.
   *
   * <p><b>Performance note:</b> the instance returned is a singleton.

            

Reported by PMD.

The String literal 'unchecked' appears 6 times in this file; the first occurrence is on line 58
Error

Line: 58

                 *
   * <p><b>Performance note:</b> the instance returned is a singleton.
   */
  @SuppressWarnings({"unchecked"}) // fully variant implementation (never actually produces any Es)
  public static <E> ImmutableSet<E> of() {
    return (ImmutableSet<E>) RegularImmutableSet.EMPTY;
  }

  /**

            

Reported by PMD.

The method 'construct(int, Object...)' has a cyclomatic complexity of 10.
Design

Line: 146

                 *
   * @throws NullPointerException if any of the first {@code n} elements of {@code elements} is null
   */
  private static <E> ImmutableSet<E> construct(int n, @Nullable Object... elements) {
    switch (n) {
      case 0:
        return of();
      case 1:
        @SuppressWarnings("unchecked") // safe; elements contains only E's

            

Reported by PMD.

The method 'construct' has a Standard Cyclomatic Complexity of 10.
Design

Line: 146

                 *
   * @throws NullPointerException if any of the first {@code n} elements of {@code elements} is null
   */
  private static <E> ImmutableSet<E> construct(int n, @Nullable Object... elements) {
    switch (n) {
      case 0:
        return of();
      case 1:
        @SuppressWarnings("unchecked") // safe; elements contains only E's

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 165

                  int uniques = 0;
    for (int i = 0; i < n; i++) {
      Object element = checkElementNotNull(elements[i], i);
      int hash = element.hashCode();
      for (int j = Hashing.smear(hash); ; j++) {
        int index = j & mask;
        Object value = table[index];
        if (value == null) {
          // Came to an empty slot. Put the element here.

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 175

                        table[index] = element;
          hashCode += hash;
          break;
        } else if (value.equals(element)) {
          break;
        }
      }
    }
    Arrays.fill(elements, uniques, n, null);

            

Reported by PMD.

Avoid using Literals in Conditional Statements
Error

Line: 181

                    }
    }
    Arrays.fill(elements, uniques, n, null);
    if (uniques == 1) {
      // There is only one element or elements are all duplicates
      @SuppressWarnings("unchecked") // we are careful to only pass in E
      // requireNonNull is safe because the first `uniques` elements are non-null.
      E element = (E) requireNonNull(elements[0]);
      return new SingletonImmutableSet<E>(element, hashCode);

            

Reported by PMD.

android/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java
35 issues
Avoid instantiating new objects inside loops
Performance

Line: 315

                  ArrayList<LockGraphNode> nodes = Lists.newArrayListWithCapacity(numKeys);
    // Create a LockGraphNode for each enum value.
    for (E key : keys) {
      LockGraphNode node = new LockGraphNode(getLockName(key));
      nodes.add(node);
      map.put(key, node);
    }
    // Pre-populate all allowedPriorLocks with nodes of smaller ordinal.
    for (int i = 1; i < numKeys; i++) {

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 321

                  }
    // Pre-populate all allowedPriorLocks with nodes of smaller ordinal.
    for (int i = 1; i < numKeys; i++) {
      nodes.get(i).checkAcquiredLocks(Policies.THROW, nodes.subList(0, i));
    }
    // Pre-populate all disallowedPriorLocks with nodes of larger ordinal.
    for (int i = 0; i < numKeys - 1; i++) {
      nodes.get(i).checkAcquiredLocks(Policies.DISABLED, nodes.subList(i + 1, numKeys));
    }

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 325

                  }
    // Pre-populate all disallowedPriorLocks with nodes of larger ordinal.
    for (int i = 0; i < numKeys - 1; i++) {
      nodes.get(i).checkAcquiredLocks(Policies.DISABLED, nodes.subList(i + 1, numKeys));
    }
    return Collections.unmodifiableMap(map);
  }

  /**

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 335

                 * used in exception and warning output.
   */
  private static String getLockName(Enum<?> rank) {
    return rank.getDeclaringClass().getSimpleName() + "." + rank.name();
  }

  /**
   * A {@code CycleDetectingLockFactory.WithExplicitOrdering} provides the additional enforcement of
   * an application-specified ordering of lock acquisitions. The application defines the allowed

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 401

                public static final class WithExplicitOrdering<E extends Enum<E>>
      extends CycleDetectingLockFactory {

    private final Map<E, LockGraphNode> lockGraphNodes;

    @VisibleForTesting
    WithExplicitOrdering(Policy policy, Map<E, LockGraphNode> lockGraphNodes) {
      super(policy);
      this.lockGraphNodes = lockGraphNodes;

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 457

              
  private static final Logger logger = Logger.getLogger(CycleDetectingLockFactory.class.getName());

  final Policy policy;

  private CycleDetectingLockFactory(Policy policy) {
    this.policy = checkNotNull(policy);
  }


            

Reported by PMD.

Classes implementing Serializable should set a serialVersionUID
Error

Line: 490

                 *   at com...MyClass.someMethodThatAcquiresLockB(MyClass.java:123)
   * </pre>
   */
  private static class ExampleStackTrace extends IllegalStateException {

    static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0];

    static final ImmutableSet<String> EXCLUDED_CLASS_NAMES =
        ImmutableSet.of(

            

Reported by PMD.

Too many control variables in the for statement
Design

Line: 503

                  ExampleStackTrace(LockGraphNode node1, LockGraphNode node2) {
      super(node1.getLockName() + " -> " + node2.getLockName());
      StackTraceElement[] origStackTrace = getStackTrace();
      for (int i = 0, n = origStackTrace.length; i < n; i++) {
        if (WithExplicitOrdering.class.getName().equals(origStackTrace[i].getClassName())) {
          // For pre-populated disallowedPriorLocks edges, omit the stack trace.
          setStackTrace(EMPTY_STACK_TRACE);
          break;
        }

            

Reported by PMD.

Classes implementing Serializable should set a serialVersionUID
Error

Line: 538

                 * @since 13.0
   */
  @Beta
  public static final class PotentialDeadlockException extends ExampleStackTrace {

    private final ExampleStackTrace conflictingStackTrace;

    private PotentialDeadlockException(
        LockGraphNode node1, LockGraphNode node2, ExampleStackTrace conflictingStackTrace) {

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 561

                  public String getMessage() {
      // requireNonNull is safe because ExampleStackTrace sets a non-null message.
      StringBuilder message = new StringBuilder(requireNonNull(super.getMessage()));
      for (Throwable t = conflictingStackTrace; t != null; t = t.getCause()) {
        message.append(", ").append(t.getMessage());
      }
      return message.toString();
    }
  }

            

Reported by PMD.