Inspectopedia Help

'synchronized' method

Reports the synchronized modifier on methods.

There are several reasons a synchronized modifier on a method may be a bad idea:

  • As little work as possible should be performed under a lock. Therefore it is often better to use a synchronized block and keep there only the code that works with shared state.

  • Synchronization becomes a part of a method's interface. This makes a transition to a different locking mechanism difficult.

  • Keeping track of what is locking a particular object gets harder.

  • The DoS (denial-of-service) attack becomes feasible either on purpose or unknowingly when inheriting the method's class.

As an alternative, consider synchronizing on a private final lock object, access to which can be completely controlled.

A quick-fix is provided to wrap the method body with synchronized(this).

Example:

class Main { public synchronized void fooBar() { } }

After the quick-fix is applied:

class Main { public void fooBar() { synchronized (this) { } } }

You can configure the following options for this inspection:

  • Include native methods - include native methods into the inspection's scope.

  • Ignore methods overriding a synchronized method - do not report methods that override a synchronized method.

Inspection options

Option

Type

Default

Include native methods

Checkbox

true

Ignore methods overriding a synchronized method

Checkbox

true

Inspection Details

Available in:

IntelliJ IDEA 2023.3, Qodana for JVM 2023.3

Plugin:

Java, 233.SNAPSHOT

Last modified: 13 July 2023