Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Holding locks while performing time-consuming or blocking operations can severely degrade system performance and can result in starvation. Furthermore, deadlock  can result if interdependent threads block indefinitely. Blocking operations include network, file, and console I/O (for example, Console.readLine()) and object serialization. Deferring a thread indefinitely also constitutes a blocking operation. Consequently, programs must not perform blocking operations while holding a lock.

When the Java Virtual Machine (JVM) interacts with a file system that operates over an unreliable network, file I/O might incur a large performance penalty. In such cases, avoid file I/O over the network while holding a lock. File operations (such as logging) that could block while waiting for the output stream lock or for I/O to complete could be performed in a dedicated thread to speed up task processing. Logging requests can be added to a queue, assuming that the queue's put() operation incurs little overhead as compared to file I/O [Goetz 2006].

Noncompliant Code Example (Deferring a Thread)

This noncompliant code example defines a utility method that accepts a time argument:

Code Block
bgColor#FFCCCC
public synchronized void doSomething(long time)
                         throws InterruptedException {
  // ...
  Thread.sleep(time);
}

Because the method is synchronized, when the thread is suspended, other threads cannot use the synchronized methods of the class. The current object's monitor continues to be held because the Thread.sleep() method lacks synchronization semantics.

Compliant Solution (Intrinsic Lock)

This compliant solution defines the doSomething() method with a timeout parameter rather than the time value. Using Object.wait() instead of Thread.sleep() allows setting a timeout period during which a notification may awaken the thread.

Code Block
bgColor#ccccff
public synchronized void doSomething(long timeout)
                                     throws InterruptedException {
// ...
  while (<condition does not hold>) {
    wait(timeout); // Immediately releases the current monitor
  }
}

The current object's monitor is immediately released upon entering the wait state. When the timeout period elapses, the thread resumes execution after reacquiring the current object's monitor.

According to the Java API Class Object documentation [API 2014]

Note that the wait method, as it places the current thread into the wait set for this object, unlocks only this object; any other objects on which the current thread may be synchronized remain locked while the thread waits.

This method should only be called by a thread that is the owner of this object's monitor.

Programs must ensure that threads that hold locks on other objects release those locks appropriately before entering the wait state. Additional guidance on waiting and notification is available in THI03-J. Always invoke wait() and await() methods inside a loop and THI02-J. Notify all waiting threads rather than a single thread.

Noncompliant Code Example (Network I/O)

This noncompliant code example defines a sendPage() method that sends a Page object from a server to a client. The method is synchronized to protect the pageBuff array when multiple threads request concurrent access

Applying a lock over a call to a method performing network transactions can be problematic.  Depending on the speed and reliability of the connection, the synchronization could lock up the program, producing temporary or permanent deadlock.

Noncompliant Code Example

This noncompliant code example involves the method send_page which sends a Page object containing information being passed between a client and server. send_packet is synchronized to protect access to the array page_buff.

Code Block
bgColor#FFcccc
public final boolean SUCCESS = true;
public final boolean FAILURE = false// Class Page is defined separately. 
// It stores and returns the Page name via getName()
Page[] pageBuff = new Page[MAX_PAGE_SIZE];

public synchronized boolean send_pagesendPage(Socket socket, String page_namepageName){ 
  try{
                                     throws IOException {
  // Get the output stream to write the Page to
  ObjectOutputStream out ObjectOutputStream
     outStream = new ObjectOutputStream(socket.getOutputStream());

  // Find the Page target_page = null;

  requested by the client
  // Find(this theoperation Pagerequires requestedsynchronization)
 by thePage client
targetPage = null;
  for (Page p : page_buffpageBuff) {
    if  if(p.getName().equalscompareTo(page_name))pageName) == 0) {
      targetPage  target_page = p;
    }

  }

  // Requested Page requested does not exist
  if  if(target_pagetargetPage == null) {
      return FAILUREfalse;

  }

  // Send the Page to the client
  // (does not require any synchronization)
  out.writeObject(target_pagetargetPage);

    out.flush();

    return SUCCESS;
  }catch(IOException io){out.close();
    // handle exception
  }
}
return true;
}

Calling writeObject() within the synchronized send_page could lead to deadlock in the event that the connection becomes slow or acknowledgments of received data are delayed or lost sendPage() method can result in delays and deadlock-like conditions in high-latency networks or when network connections are inherently lossy.

Compliant Solution

A solution would be to separate actions into This compliant solution separates the process into a sequence of steps:

  1. Perform actions on data structures requiring synchronization.

...

  1. Create copies of

...

  1. the objects to

...

  1. be sent.
  2. Perform network calls in a separate unsynchronized method.

In the following example, the synchronized method get_page is called to find the appropriate Page requested by the client from the Page array page_buff. It then calls the method send_page (which has no synchronization applied to it) to send the Pagethis compliant solution, the unsynchronized sendPage() method calls the synchronized getPage() method to retrieve the requested Page in the pageBuff array. After the Page is retrieved, sendPage() calls the unsynchronized deliverPage() method to deliver the Page to the client.

Code Block
bgColor#ccccff
public// final boolean SUCCESS = true;No synchronization
public final boolean FAILURE = false;

public boolean send_replysendPage(Socket socket, String page_namepageName) {
  Page target_pagetargetPage = get_page(page_namegetPage(pageName);

  if (target_pagetargetPage == null){
    return FAILUREfalse;
  }
  return send_pagedeliverPage(Socket socket, target_pagetargetPage);
}

// Requires synchronization
private synchronized Page get_pagegetPage(String page_namepageName) {
  Page target_pagetargetPage = null;

  for (Page p : page_buffpageBuff) {
    if (p.getName().equals(page_namepageName)) {
      target_pagetargetPage = p;
    }
  }
  return target_pagetargetPage;
}

// Return false if an error occurs, true if successful
public boolean send_pagedeliverPage(Socket socket, Page page) {
  ObjectOutputStream out = null;
  boolean result = true;
  try {
    // Get the output stream to write the Page to
    ObjectOutputStreamout outStream = new ObjectOutputStream(socket.getOutputStream());

    // Send the Pagepage to the client
    out.writeObject(page);out.flush();
  } catch out.flush(IOException io) {
    result = false;
  } finally {
    if (out != null) {
      try {
    return SUCCESS    out.close();
      } catch (IOException ioe) {
     // handle exception

   result = false;
      }
    }
 return FAILURE;}
  return }
}
result;
}

Exceptions

LCK09-J-EX0: Classes that provide an appropriate termination mechanism to callers are permitted to violate this rule (see THI04-J. Ensure that threads performing blocking operations can be terminated).

LCK09-J-EX1: Methods that require multiple locks may hold several locks while waiting for the remaining locks to become available. This constitutes a valid exception, although the programmer must follow other applicable rules, especially LCK07-J. Avoid deadlock by requesting and releasing locks in the same order to avoid deadlock .

Risk Assessment

Application of synchronization or locks to methods that perform transactions over a network can lead to temporary or permanent deadlocksBlocking or lengthy operations performed within synchronized regions could result in a deadlocked or unresponsive system.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON37

LCK09-J

low

Low

unlikely

Probable

high

High

P1

L3

P2

L3

Automated Detection

Some static analysis tools are capable of detecting violations of this rule.

ToolVersionCheckerDescription
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

JAVA.CONCURRENCY.STARVE.BLOCKING

Blocking in Critical Section (Java)

Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.LCK09.TSHL
CERT.LCK09.TSHL2
Do not use blocking methods while holding a lock
Do not call 'Thread.sleep()' while holding a lock since doing so can cause poor performance and deadlocks
PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V6095
ThreadSafe
Include Page
ThreadSafe_V
ThreadSafe_V

CCE_LK_LOCKED_BLOCKING_CALLS

Implemented
SonarQube
Include Page
SonarQube_V
SonarQube_V
S2276Implemented

Related Guidelines

Bibliography


...

Image Added Image Added Image Added