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.

Wiki Markup
IfWhen the 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 could block 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|AA. Bibliography#Goetz 06]\].

...

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 are unable to 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.

...

Code Block
bgColor#ccccff
public synchronized void doSomething(long timeout)
                                     throws InterruptedException {

  while (<condition does not hold>) {
    wait(timeout); // Immediately releases current monitor
  }
}

The current object's monitor is immediately released upon entering the wait state. After the time out timeout period has elapsed, the thread resumes execution after reacquiring the current 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 rules THI03-J. Always invoke wait() and await() methods inside a loop and THI02-J. Notify all waiting threads rather than a single thread.

...

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

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

  // Find the Page requested by the client
  // (this operation requires synchronization)
  Page targetPage = null;
  for (Page p : pageBuff) {
    if (p.getName().compareTo(pageName) == 0) {
      targetPage = p;
    }
  }

  // Requested Page does not exist
  if (targetPage == null) {
    return false;
  }

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

  out.flush();
  out.close();
  return true;
}

Calling writeObject() within the synchronized sendPage() method can result in delays and deadlock-like conditions in high-latency networks or when network connections are inherently lossy.

...

In this compliant solution, the synchronized getPage() method is called from an unsynchronized sendPage() 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
// No synchronization
public boolean sendPage(Socket socket, String pageName) { // No synchronization
  Page targetPage = getPage(pageName);

  if (targetPage == null)
    return false;

  return deliverPage(socket, targetPage);
}

// Requires synchronization
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 Pagepage 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;
}

...

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

LCK09-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 to avoid deadlock. See , especially rule LCK07-J. Avoid deadlock by requesting and releasing locks in the same order for more information to avoid deadlock.

Risk Assessment

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

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="42bdc26d1eddf5dd-a4cebb92-4bf84143-8a329478-e512f8c76daafc8d8d295e49"><ac:plain-text-body><![CDATA[

[[API 2006

AA. Bibliography#API 06]]

Class Object

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="9ca4d5603443cdd6-5885eede-4aef4662-bfcb8adc-64b25a638ea500b78ae40d58"><ac:plain-text-body><![CDATA[

[[Grosso 2001

AA. Bibliography#Grosso 01]]

[Chapter 10: , Serialization

http://oreilly.com/catalog/javarmi/chapter/ch10.html]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="bcc3e9c3142bf0a6-70959c17-45f24410-9bd48700-178612f80b347031740c743f"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

[Chapter 17, Threads and Locks

http://java.sun.com/docs/books/jls/third_edition/html/memory.html]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="0d666e9a625e8741-51e690d4-4ecb494b-93a2b9c9-df15e0718c04a7c66c214ac6"><ac:plain-text-body><![CDATA[

[[Rotem 2008

AA. Bibliography#Rotem 08]]

[Falacies Fallacies of Distributed Computing Explained

http://www.rgoarchitects.com/Files/fallacies.pdf]

]]></ac:plain-text-body></ac:structured-macro>

...