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.
...
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 is 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 compliant solution separates the process into a sequence of steps:
- Perform actions on data structures requiring synchronization.
- Create copies of the objects to be sent.
- Perform network calls in a separate method that does not require any synchronization.
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.
...