Detectors

This document lists all detectors in SpotBugs.

Standard detectors

These detectors are on by default:

AppendingToAnObjectOutputStream

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

AtomicityProblem

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

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.

BadSyntaxForRegularExpression

This detector looks for regular expressions that have invalid syntax.

BadUseOfReturnValue

Looks for cases where the return value of a function is discarded after being checked for non-null.

BadlyOverriddenAdapter

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

BooleanReturnNull

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

CheckImmutableAnnotation

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

CheckRelaxingNullnessAnnotation

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

ComparatorIdiom

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

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.

ConfusionBetweenInheritedAndOuterMethod

Looks for potential confusion between inherited and outer methods.

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.

DontCatchIllegalMonitorStateException

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

DontIgnoreResultOfPutIfAbsent

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

DontUseEnum

Checks that fields and methods don't use the name assert or enum as they are keywords in Java 5.

DroppedException

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

DumbMethods

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

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.

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.

ExplicitSerialization

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

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.

FindBadForLoop

This detector looks for incorrect for loops.

FindComparatorProblems

This detector looks for problems in Comparator.compare or Comparable.compareTo implementation.

FindDoubleCheck

This detector looks for instances of double checked locking.

FindEmptySynchronizedBlock

This detector looks for empty synchronized blocks.

FindFieldSelfAssignment

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

FindFloatEquality

Looks for floating point equality expressions. A fast detector.

FindInconsistentSync2

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

FindJSR166LockMonitorenter

This detector looks for ordinary synchronization performed on JSR166 locks. It is a moderately fast detector.

FindLocalSelfAssignment2

This detector looks for self assignments of local variables.

FindMaskedFields

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

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.

FindNakedNotify

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

FindNonShortCircuit

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

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.

FindOpenStream

This detector looks for IO stream objects which do not escape the method and do not appear to be closed on all paths out of the method. It is a slow detector.

FindRoughConstants

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

FindRunInvocations

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

FindSleepWithLockHeld

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

FindSpinLoop

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

FindSqlInjection

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

FindTwoLockWait

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

FindUncalledPrivateMethods

This detector looks for private methods that are never called.

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.

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.

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).

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.

FindUnsyncGet

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

FindUseOfNonSerializableValue

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

FindUselessControlFlow

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

FindUselessObjects

Looks for useless objects.

HugeSharedStringConstants

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

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.

InconsistentAnnotations

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

InfiniteLoop

Looks for an infinite loop.

InfiniteRecursiveLoop

Looks for an infinite recursive 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.

InitializationChain

This detector looks for potentially circular class initialization dependencies.

InitializeNonnullFieldsInConstructor

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

InstantiateStaticClass

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

IntCast2LongAsInstant

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

IteratorIdioms

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

LazyInit

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

LoadOfKnownNullValue

Looks for loads of values known to be null.

LostLoggerDueToWeakReference

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

MultithreadedInstanceAccess

This detector looks for potential problems in implementing the Struts framework.

MutableLock

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

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.

OptionalReturnNull

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

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.

QuestionableBooleanAssignment

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

ReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass

Checks for methods invoked from constructors for superclasses.

ReadReturnShouldBeChecked

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

RedundantConditions

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

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.

RepeatedConditionals

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

RuntimeExceptionCapture

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

StartInConstructor

This detector looks for constructors that start threads.

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.

StringConcatenation

This detector looks for String concatenation in loops using +.

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.

SynchronizationOnSharedBuiltinConstant

This detector looks for synchronization on a shared built-in constant (such as a String).

SynchronizeAndNullCheckField

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

SynchronizeOnClassLiteralNotGetClass

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

SynchronizingOnContentsOfFieldToProtectField

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

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.

UncallableMethodOfAnonymousClass

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

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.

VarArgsProblems

Looks for problems with arising from Java 1.5 var args.

WaitInLoop

This detector looks for calls to wait() that are not in a loop.

WrongMapIterator

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

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.

Disabled detectors

These detectors are off by default:

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.

CallToUnsupportedMethod

This detector looks for calls to methods that are unsupported.

CheckExpectedWarnings

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

CovariantArrayAssignment

This detector looks for covariant array assignments like Object[] array = new String[10] which may cause ArrayStoreException at runtime.

EmptyZipFileEntry

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

FindCircularDependencies

This detector looks for circular dependencies among classes.

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.

InefficientInitializationInsideLoop

This detector looks for objects initialized within loop which can be moved outside for better performance.

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.

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.

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.

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.