Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: edits

Holding locks while performing time consuming or blocking operations can severely degrade system performance and result in starvation. Furthermore, deadlock may result if too many interdependent threads block. Blocking operations include network, file and console I/O (for instance, invoking methods a method such as Console.readLine()) and letting . Deferring a thread defer itself 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 also incur a performance penalty. In such cases, avoid file I/O over the network while 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 {{put()}} operation incurs little overhead as compared to file I/O \[[Goetz 06, pg 244|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. In other words, the current object's monitor is not released. This is because the Thread.sleep() method does not have any synchronization semantics, as detailed in CON16-J. Do not expect sleep(), yield() and getState() methods to have any synchronization semantics.

Compliant Solution (intrinsic lock)

This compliant solution defines the synchronized doSomething() 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 during which a notify signal may awaken the thread.

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

...

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 array pageBuff is accessed safely , when multiple threads request concurrent access.

...

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

...