Detectors

This document lists all detectors in SpotBugs.

Standard detectors

These detectors are on by default:

FindRoughConstants

Finds constants which roughly (but not precisely) equal to known values like Math.PI.

SynchronizeAndNullCheckField

This detector looks for a field that is synchronized on and then null checked.

InitializeNonnullFieldsInConstructor

Finds non-null fields that are not written to in constructors.

BooleanReturnNull

Looks for methods with Boolean return type that return explicit null values.

OptionalReturnNull

Looks for methods with Optional return type that return explicit null values.

ConfusionBetweenInheritedAndOuterMethod

Looks for potential confusion between inherited and outer methods.

NoteUnconditionalParamDerefs

Analyze all methods in the application to determine which dereference parameters unconditionally. This information is used in a later analysis pass to find call sites where null values may be passed to those methods.

This is a slow detector.

SynchronizeOnClassLiteralNotGetClass

Looks for code that synchronizes on the results of getClass rather than on class literals.

InfiniteLoop

Looks for an infinite loop.

InheritanceUnsafeGetResource

Looks for uses of this.getClass().getResource(...), which can give unexpected results if the class is extended by a class in another package.

HugeSharedStringConstants

This detector looks for string constants that are duplicated across multiple classfiles.

FinalizerNullsFields

This detector looks for finalizers that null out fields of a class. This does not help the garbage collector in any way, the nulling out of fields has no effect.

InconsistentAnnotations

This detector finds inconsistencies between type qualifiers directly applied to method parameters and uses of those method parameters.

RepeatedConditionals

This detector looks for code containing repeated conditional tests, such as (x == 5 || x == 5).

RedundantConditions

This detector looks for code containing useless conditions like the second condition in this expression: (x >= 10 && x >= 5).

FormatStringChecker

Checks for incorrect format strings.

LostLoggerDueToWeakReference

This detector finds code that behaves differently under OpenJDK 1.6, where weak references are used to hold onto Loggers.

EqualsOperandShouldHaveClassCompatibleWithThis

Checks for equals methods that check for their operand being an instance of a class that is not compatible with the class defining the equals method.

CheckImmutableAnnotation

Looks for violations of the rules for classes annotated as net.jcip.annotations.Immutable or javax.annotation.concurrent.Immutable.

DontCatchIllegalMonitorStateException

This detector looks for try-catch blocks that catch an IllegalMonitorStateException.

ComparatorIdiom

This detector looks for violations of the idioms for writing classes that implement Comparator.

FindFieldSelfAssignment

This detector looks for places where a field is assigned by reading the value of the same field.

DroppedException

This detector looks for code where an exception is caught, but nothing is done to handle the exception.

LoadOfKnownNullValue

Looks for loads of values known to be null.

URLProblems

The equals and hashCode method on java.net.URL resolve the domain name. As a result, these operations can be very expensive, and this detector looks for places where those methods might be invoked.

DumbMethods

This detector looks for calls to pointless methods, such as the no-argument String constructor.

FindSqlInjection

This detector uses data flow analysis to look for invocations of execute methods on SQL statements in which something other than a constant string is passed as an argument.

FindHEmismatch

This detector looks for problems in the definition of the hashCode() and equals() methods.

FindNakedNotify

This detector looks for calls to notify() that don't seem to modify mutable object state.

FindRunInvocations

This detector looks for calls to Thread.run(). It is a fast detector.

FindSpinLoop

This detector looks for loops that spin reading from a field.

FindNonShortCircuit

This detector looks for suspicious uses of non-short-circuiting boolean operators (| and & instead of || and &&).

FindTwoLockWait

This detector looks for calls to wait() with two (or more) locks held. It is a slow detector.

FindUnconditionalWait

This detector looks for calls to wait() not in a conditional or loop.

FindUninitializedGet

This detector looks for reads of uninitialized fields in constructors.

FindUnsyncGet

This detector looks for get and set methods where the get is unsynchronized while the set is synchronized.

IteratorIdioms

This detector looks for problems in how Iterator classes are defined.

PreferZeroLengthArrays

This detector looks for methods that return either arrays or an explicit null reference. Returning a zero length array is generally preferred in this context to returning a null reference.

SynchronizingOnContentsOfFieldToProtectField

This detector looks for code that seems to be synchronizing on a field in order to guard updates of that field.

MutableLock

This detector looks for synchronization on objects read from modified fields.

ReadReturnShouldBeChecked

This detector looks for calls to InputStream.read() or InputStream.skip() where the return value is ignored.

SerializableIdiom

This detector looks for potential problems in the implementation of Serializable classes.

StartInConstructor

This detector looks for constructors that start threads.

FindBadForLoop

This detector looks for incorrect for loops.

ExplicitSerialization

Looks for explicit serialization via readObject and writeObject as evidence that this class is, indeed, serialized.

  • :ref:``

FindNullDeref

This detector looks for places where a null pointer exception might occur. It also looks for redundant comparisons of reference values against null. It is a slow detector.

FindNullDerefsInvolvingNonShortCircuitEvaluation

This detector looks for places where a null pointer exception might occur, and the use of non-short-circuit evaluation causes the usual techniques to fail.

FindUselessControlFlow

This detector looks for control flow statements which have no effect.

FindUnreleasedLock

This detector looks for JSR-166 (java.util.concurrent) locks which are acquired, but not released on all paths out of the method.  It is a moderately fast detector.  Note that in order to use this detector, you need to have the java.util.concurrent package in the auxiliary classpath (or be analyzing the package itself).

FindMismatchedWaitOrNotify

This detector looks for calls to wait(), notify(), or notifyAll() which do not appear to be made on an object which is currently locked.  It is a moderately fast detector.  This detector is disabled because it is still under development, and produces too many false positives.

FindEmptySynchronizedBlock

This detector looks for empty synchronized blocks.

FindInconsistentSync2

This detector looks for fields that are accessed in an inconsistent manner with respect to locking. It is a slow detector.

LazyInit

This detector looks for lazy field initialization where the field is not volatile. It is a moderately fast detector.

FindUncalledPrivateMethods

This detector looks for private methods that are never called.

UncallableMethodOfAnonymousClass

This detector looks for anonymous inner classes that define methods that are probably intended to but do not override methods in a superclass.

StringConcatenation

This detector looks for String concatenation in loops using +.

BadlyOverriddenAdapter

This detector looks for code that extends an Adapter class and overrides a Listener method with the wrong signature.

BadResultSetAccess

This detector looks for calls to getXXX or setXXX methods of a result set where the field index is 0. As ResultSet fields start at index 1, this is always a mistake.

SuperfluousInstanceOf

This detector looks for type checks using the instanceof operator where the determination can be done statically.

SuspiciousThreadInterrupted

This detector looks for calls to Thread.interrupted() from a non-static context. If it is called from Thread.currentThread().interrupted(), then it is just a useless exercise, just use Thread.interrupted(). However if it is called on an arbitrary thread object, it is most probably an error, as interrupted() is always called on the current thread.

FindMaskedFields

This detector looks for class level fields that are masked by local fields defined in methods.

WrongMapIterator

This detector looks for accessing the value of a Map entry, using a key that was retrieved from a keySet iterator.

InstantiateStaticClass

This detector looks for code that creates objects based on classes that only define static methods.

RuntimeExceptionCapture

This detector looks for catch clauses that catch Exception, when no code in the block throws Exception.

FindUnsatisfiedObligation

This detector looks for I/O streams and database resources that are not cleaned up on all paths out of a method. This is a slow detector.

UnnecessaryMath

This detector looks for code that calls java.lang.Math static methods on constant values, where the resultant value is a statically known constant. It is faster, and sometimes more accurate, to use the constant instead.

RedundantInterfaces

This detector looks for classes that declare they implement the same interface as a super class. This is redundant, if a superclass implements an interface, so does the subclass.

IDivResultCastToDouble

This detector looks for places where the result of integer division is cast to double. Often, what was meant was to cast the integer operands to double and then perform the division.

FindUseOfNonSerializableValue

This detector looks for uses of non Serializable objects in contexts that require them to be serializable.

FindPuzzlers

This detector looks for miscellaneous small errors mentioned by Joshua Bloch and Neal Gafter in their work on Programming Puzzlers.

IntCast2LongAsInstant

Finds uses of 32-bit values to describe milliseconds since the epoch.

FindSleepWithLockHeld

This detector looks for calls to Thread.sleep() made with a lock held. It is a slow detector.

DuplicateBranches

This detector looks for if/else or switch statements that have the same code for two branches, thus rendering the test useless. This often is caused by copying and pasting the two branches, causing incorrect logic for the one branch.

XMLFactoryBypass

This detector looks for direct allocations of implementations of XML interfaces. This ties the code to a specific implementation, rather than using the supplied factory pattern to create these objects.

ConfusedInheritance

This detector looks for final classes that declare protected members. As this class can not be derived from, the use of protected access for members is incorrect. The access should be changed to public or private to represent the correct intention of the field. This was probably caused by a change in use for this class, without completely changing all of the class to the new paradigm.

QuestionableBooleanAssignment

This detector looks for simple assignments of literal boolean values to variables in conditional expressions.

AppendingToAnObjectOutputStream

Looks for an attempt to append to an object output stream.

FindUnrelatedTypesInGenericContainer

This detector looks at the arguments of calls to generic collection methods that receive a java.lang.Object to see if the argument's type is related to the collection's parameter. Arguments with unrelated class types are never going to be in the collection. For example, if foo is a List<String> and bar is a StringBuffer, the call foo.contains(bar) will always return false. This is a fast detector.

StaticCalendarDetector

This detector warns about static fields of type java.util.Calendar or java.text.DateFormat (and subclasses) because Calendars are inherently unsafe for multithreaded use.

DontIgnoreResultOfPutIfAbsent

Checks that if the result of putIfAbsent is ignored, the value passed as the second argument is not reused.

ReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass

Checks for methods invoked from constructors for superclasses.

AtomicityProblem

Finds sequences of operations (e.g., get/put) on a concurrent abstraction that will not be executed atomically.

DefaultEncodingDetector

Checks for calls to methods which perform a byte to String (or String to byte) conversion using the user's default platform encoding. This can cause the application behaviour to vary between platforms.

CheckRelaxingNullnessAnnotation

Checks that overriding methods do not relax @Nonnull (made @CheckForNull) on return values or @CheckForNull (made @Nonnull) on parameters.

DontAssertInstanceofInTests

Detector for patterns in JUnit tests where the type of an object is checked by asserting the instanceof operator.

This should be avoided as the ClassCastException that would result from an improper cast may provide more information regarding the cause of the error than a "false is not true" message which would result from asserting the result of the instanceof operator.

It is a fast detector

FindBadEndOfStreamCheck

Detector for patterns where the return value of java.io.FileInputStream.read() or java.io.FileReader.read() is converted before checking against -1.

Both methods return an int. If this int is converted to byte (in the case of FileInputStream.read()) then -1 and the byte 0xFF become indistinguishable. If it is converted to char (in the case of FileReader.read()) then -1 becomes 0xFFFF which is Character.MAX_VALUE since characters are unsigned in Java.

Disabled detectors

These detectors are off by default:

EmptyZipFileEntry

This looks for creation of empty zip file entries. It is a moderately fast detector.

CallToUnsupportedMethod

This detector looks for calls to methods that are unsupported.

InefficientIndexOf

This detector looks for code that uses String.indexOf(String) or String.lastIndexOf(String), passing a constant string of length 1. It is recommended to use the more efficient integer implementations. A fast detector.

InefficientToArray

This detector looks for code that converts Collections to arrays using the toArray() method that takes a prototype array, passing an array argument which is zero-length.

BadAppletConstructor

This detector looks for Applet constructors that call methods in the parent Applet that rely on the Applet stub. Since this stub isn't initialized until just before the init() method, these methods will fail in the constructor.

FindCircularDependencies

This detector looks for circular dependencies among classes.

PublicSemaphores

This detector looks for public classes that synchronize and use wait(), notify() or notifyAll() on this. This exposes a synchronization implementation as a public artifact of the class. Clients of the class may use an instance of the class as its own synchronizing object, and cause havoc to the base implementation.

InefficientMemberAccess

This detector looks for internal classes that write to member variables of the owning class, when that member variable is private. In this case, a special compiler generated accessor method needs to be used to write to this variable. Relaxing the visibility to protected will allow the field to be directly written.

UselessSubclassMethod

This detector looks for subclasses that implement methods defined in the super class, that only pass the parameters untouched to the parent class method. These methods can just be removed.

CheckExpectedWarnings

Checks @ExpectedWarning and @NoWarning annotations. This detector is used only for testing SpotBugs.