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

Wiki Markup
If 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 when holding a lock. File operations (such as logging) that may block waiting for the output stream lock or for I/O to complete may be performed in a dedicated thread to speed up task processing. Logging requests can be added to a queue given that the queue's {{put()}} operation incurs little overhead as compared to file I/O \[[Goetz 062006|AA. Java References#Goetz 06]\].

...

Because the method is synchronized, if the thread is suspended, other threads are unable to use the synchronized methods of the class. The current object's monitor is not released because the Thread.sleep() method does not have any synchronization semantics, as detailed in guideline THI00-J. Do not assume that the sleep(), yield() or getState() methods provide synchronization semantics.

...

Wiki Markup
According to the Java API class {{Object}} documentation \[[API 062006|AA. Java References#API 06]\]:

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.

Ensure that a thread that holds locks on other objects releases them appropriately, before entering the wait state. Additional guidance on waiting and notification in available in guidelines THI03-J. Always invoke wait() and await() methods inside a loop and THI04-J. Notify all waiting threads instead of a single thread.

...

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

...

This compliant solution separates the process into a sequence of steps:

  1. Perform actions on data structures requiring synchronization.
  2. Create copies of the objects to be sent.
  3. Perform network calls in a separate method that does not require any synchronization.

In this compliant solution, the synchronized method getPage() method is called from an unsynchronized method sendPage(), method to retrieve the requested Page in the pageBuff array. After the Page is retrieved, sendPage() calls the unsynchronized method deliverPage() method to deliver the Page to the client.

Code Block
bgColor#ccccff
public boolean sendPage(Socket socket, String pageName) { // No synchronization
  Page targetPage = getPage(pageName);

  if (targetPage == null)
    return false;

  return deliverPage(socket, targetPage);
}

private synchronized Page getPage(String pageName) { // Requires synchronization
  Page targetPage = null;

  for (Page p : pageBuff) {
    if (p.getName().equals(pageName)) {
      targetPage = p;
    }
  }
  return targetPage;
}

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

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

Exceptions

LCK09-EX1: Classes that provide an appropriate termination mechanism to callers are allowed to violate this guideline (see CON26guideline THI06-J. Ensure that threads performing blocking operations can be terminated).

LCK09-EX2: A method that requires multiple locks may hold several locks while waiting for the remaining locks to become available. This constitutes a valid exception, though care must be taken although the programmer must follow other applicable guidelines to avoid deadlock. See guideline LCK07-J. Avoid deadlock by requesting and releasing locks in the same order for more information.

...

Blocking or lengthy operations performed within synchronized regions may result in a deadlocked or unresponsive system.

Rule Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

CON25 LCK09-J

low

probable

high

P2

L3

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[API 062006|AA. Java References#API 06]\] Class {{Object}}
\[[Grosso 012001|AA. Java References#Grosso 01]\] [Chapter 10: Serialization|http://oreilly.com/catalog/javarmi/chapter/ch10.html]
\[[JLS 052005|AA. Java References#JLS 05]\] [Chapter 17, Threads and Locks|http://java.sun.com/docs/books/jls/third_edition/html/memory.html]
\[[Rotem 082008|AA. Java References#Rotem 08]\] [Falacies of Distributed Computing Explained|http://www.rgoarchitects.com/Files/fallacies.pdf]

...