What are the dangers of calling alien methods while holding a lock?
An "alien" method is any method that your code doesn't fully control at the point you're calling it -- typically a callback, a listener, or some other externally supplied method whose implementation is unknown or overridable. Calling such a method while still holding a lock is risky for several reasons. If the alien method itself tries to acquire another lock, it can create a deadlock, especially if some other thread is holding that second lock and waiting on the first. If the alien method calls back into your own class's synchronized methods, the behavior can be surprising even though intrinsic locks are reentrant, because the reentrant call happens with your object in a possibly unexpected intermediate state. And if the alien method is simply slow, every other thread waiting on your lock is now blocked for that entire duration, which can lead to starvation. The fix is to hold the lock only long enough to read or update your own state, copying out whatever data you need, and to invoke any alien methods only after releasing the lock. This practice, often called making "open calls" -- invoking methods while holding no lock at all -- dramatically reduces the risk of deadlock in a system.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response