Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double @synchronized: is it needed?

I'm developing an iOS application with latest SDK.

My app is a port from an Android application and I have these two methods:

- (MyObject*)getMyObject:(MyObjectType)myObjectType
{
    @synchronized(self)
    {
        for (int index = 0; index < [myObjects count]; index++)
        {
            MyObject* myObject = (MyObject*)[myObjects objectAtIndex:index];
            if (myObject.Type == myObjectType)
                return myObject;
        }

        return nil;
    }
}

- (BOOL)isMyObjectVisible:(MyObjectType)myObjectType
{
    @synchronized(self)
    {
        return ([self getMyObject:myObjectType] != nil);
    }
}

I have isMyObjectVisible:, that is @synchronized, calling another @synchronized method.

Is it necessary that isMyObjectVisible: has to be @synchronized?

like image 769
VansFannel Avatar asked Mar 04 '26 00:03

VansFannel


1 Answers

To answer your first question, no, the double locking is not needed.

You can keep the lock in getMyObject. That protects it. However, there is nothing in isMyObjectVisible other than a call to getMyObject, so there's nothing else to protect in that method.

However, borrrden's comment is not an issue here. You get a recursive lock when using @synchronized, so you can nest synchronized calls like you're doing without a deadlock. There's just no need to, in your case.

like image 88
Nate Avatar answered Mar 06 '26 12:03

Nate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!