views:

70

answers:

2

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

A: 

It is equally flawed - you have a race condition

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

Will
A: 

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

- (void) startStreaming:(NSArray *)watchlistInstrumentData {
        @synchronized(self) {
            if (!self.isStreaming) {
...
JeremyP
I was avoiding the cost of entering the synchronized block if it wasn't necessary.
bandejapaisa
That's what I meant by "premature optimisation". Why would you care about the cost of entering the synchronized block unless you had measured it with a profiler and it was taking a significant amount of time?
JeremyP