Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: merged with CON06-J

It is often insecure to hold Holding a lock while performing network transactions. Depending on the speed and reliability of the connection, held locks can stall the program indefinitely causing a huge performance hit. At other times, it can result in temporary or permanent deadlockoperations that may block degrades performance, as threads that require the lock must wait for an unrelated block to finish. Furthermore, deadlock may result if too many interdependent threads block. Blocking operations includes network I/O, and letting a thread defer itself.

If the JVM is operating on a platform that uses a file system that operates over the network, then file I/O might also suffer the same performance hits as networked I/O. If such a platform is in use, then file I/O to files over the network should also not be performed while locks are helda lock is held.

Noncompliant Code Example (intrinsic lock)

This noncompliant code example defines a utility method that accepts a time parameter. Since the method is synchronized, if the thread is suspended, other threads are unable to use the synchronized methods of the class. In other words, the current object's monitor is not released.

Code Block
bgColor#FFCCCC

private synchronized void doSomething(long time)
  throws InterruptedException {
  // ...
  Thread.sleep(time);
}

Compliant Solution (intrinsic lock)

This compliant solution defines the synchronized method with a timeout parameter instead of the time value. The use of the Object.wait() method instead of Thread.sleep() allows setting a time out for a period in which a notify signal may awaken the thread. The current object's monitor is immediately released upon entering the wait state. After the time out period has elapsed, the thread attempts to reacquire the current object's monitor and resumes execution when it succeeds.

Code Block
bgColor#ccccff

private synchronized void doSomething( long timeout)
  throws InterruptedException {
 
  while (<condition does not hold>) {
    wait(timeout); // Immediately releases lock on current monitor
  }
}

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

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.

Consequently, ensure that a thread that holds locks on other objects releases them appropriately, before entering the wait state. Also, refer to the related guidelines CON18-J. Always invoke wait() and await() methods inside a loop and CON19-J. Notify all waiting threads instead of a single thread.

Noncompliant Code Example

...

Code Block
bgColor#FFcccc
// Class Page is defined separately. It stores and returns the Page name via getName()

public final boolean SUCCESS = true;
public final boolean FAILURE = false;
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 FAILURE;
  } 

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

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

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.

...

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

  if(targetPage == null)
    return FAILURE;

  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;
}

public boolean deliverPage(Socket socket, Page page){
  try{
    // Get the output stream to write the Page to
    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());

    // Send the Page to the client
    out.writeObject(page);

  } catch(IOException io){
    // If recovery is not possible return FAILURE
    return FAILURE;    
  } finally {
    out.flush();
    out.close();
  }  
  return SUCCESS;
}

Exceptions

CON20:EX1: A method that requires multiple locks may hold several locks while waiting for the remaining locks to be available. This constitutes a valid exception, but it must be done carefully to avoid deadlock. See CON12-J. Avoid deadlock by requesting and releasing locks in the same order for more information.

Risk Assessment

If a lock is held by a block that contains network transactional logic or thread deferrment, temporary or permanent deadlocks may result.

...

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

References

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

...