user4951
user4951

Reputation: 33090

Is there a sample code where @synchronized will deadlock?

I really can't think of any

One thing I can think of is

@synchronized (self)
{
@synchronized (self){}
}

But this won't deadlock because the lock is recursive and will just allow the same thread to go through. So basically you can't deadlock if for the whole program you only use one variable

Another I can think of is

@synchronized (A)
{
@synchronized (B){}
}

in one thread and

@synchronized (B)
{
@synchronized (A){}
}

in another. Am I correct here?

How to avoid deadlock then? Any simple rules?

Upvotes: 2

Views: 923

Answers (2)

bbum
bbum

Reputation: 162712

Nothing is simple when using concurrency where there are shared resources; there is always risk of deadlock, always risk of data corruption through non-atomicity, and always the risk that fully concurrent enabled code will be slower than single-threaded code because of all the locking.

The "best" pattern is isolation; make the cross-thread/queue layer is small as possible and make everything behind it isolated to a single thread.

Core Data is a good example of this pattern. The managed object contexts are per-thread and CD manages concurrent data storage entirely behind the scenes through an exceptionally well unit-tested bit of infrastructure.

Upvotes: 1

Rich O'Kelly
Rich O'Kelly

Reputation: 41767

My #1 rule is never lock on anything that is publicly visible.
My #2 rule is never call out to external code whilst holding a lock.

I've found that if you can manage these two points, any deadlocks that could arise are far easier to spot and much easier to fix.

Upvotes: 4

Related Questions