bandejapaisa
bandejapaisa

Reputation: 173

double checked locking - objective c

I realised double checked locking is flawed in java due to the memory model, but that is usually associated with the singleton pattern and optimizing the creation of the singleton.

What about under this case in objective-c:

I have a boolean flag to determine if my application is streaming data or not. I have 3 methods, startStreaming, stopStreaming, streamingDataReceived and i protect them from multiple threads using:

- (void) streamingDataReceived:(StreamingData *)streamingData {
    if (self.isStreaming) {
        @synchronized(self) {
            if (self.isStreaming) {

- (void) stopStreaming {
    if (self.isStreaming) {
        @synchronized(self) {
            if (self.isStreaming) {

- (void) startStreaming:(NSArray *)watchlistInstrumentData {
    if (!self.isStreaming) {
        @synchronized(self) {
            if (!self.isStreaming) {

Is this double check uneccessary? Does the double check have similar problems in objective-c as in java? What are the alternatives to this pattern (anti-pattern).

Thanks

Upvotes: 5

Views: 801

Answers (2)

JeremyP
JeremyP

Reputation: 86671

That looks like premature optimisation to me. What's wrong with (for example)

- (void) startStreaming:(NSArray *)watchlistInstrumentData {
        @synchronized(self) {
            if (!self.isStreaming) {
...

Upvotes: 0

Will
Will

Reputation: 75673

It is equally flawed - you have a race condition

You have to enter your synchronized section and then check the flag

Upvotes: 2

Related Questions