Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 407
bandejapaisa Avatar asked Nov 06 '22 12:11

bandejapaisa


1 Answers

It is equally flawed - you have a race condition

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

like image 144
Will Avatar answered Nov 12 '22 11:11

Will