16 апр. 2009 г.

Java: Классический dead lock

Классический dead lock (Java Concurrency In Practice, p.10.1):
When a thread holds a lock forever, other threads attempting to acquire that lock will block forever waiting. When thread A holds lock L and tries to acquire lock M, but at the same time thread B holds M and tries to acquire L, both threads will wait forever. This situation is the simplest case of deadlock (or deadly embrace), where multiple threads wait forever due to a cyclic locking dependency. (Think of the threads as the nodes of a directed graph whose edges represent the relation "Thread A is waiting for a resource held by thread B". If this graph is cyclical, there is a deadlock.)

Пример иллюстрирующий пробему:
Есть сущность типа счёт, необходимо реализовать сервис типа переводчика денег с одного счёта на другой.

Для определённости стоит уточнить, что счетов с системе очень много (скажем, несколько миллионов) и порядка несколько тысяч операций в секунду (всё многопоточно).