Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is NSURLCache thread safe?

I know NSCache is thread safe, however I can't find out any document mentioned that NSURLCache is thread safe.

like image 683
Pei Avatar asked Feb 12 '14 23:02

Pei


3 Answers

Unless the documentation explicitly says that NSURLCache is thread safe, then it is not thread safe.

(The docs say nothing about threads. Therefore, not thread safe.)

And always check the docs again every now and then. The thread safety rules have changed since I wrote this answer.

like image 71
bbum Avatar answered Nov 14 '22 12:11

bbum


Allow me to merge the two brilliant answers into a third one, now with a reference to the updated documentation:

Thread Safety

In iOS 8 and later, and macOS 10.10 and later, NSURLCache is thread safe.

Although NSURLCache instance methods can safely be called from multiple execution contexts at the same time, be aware that methods like cachedResponseForRequest: and storeCachedResponse:forRequest: have an unavoidable race condition when attempting to read or write responses for the same request.

Subclasses of NSURLCache must implement overridden methods in such a thread safe manner.

That is, unless you explicitly call cachedResponseForRequest:, storeCachedResponse:forRequest: or other "methods alike", you'll be safe across threads. What "methods like" these are, seems to be an exercise left for the reader, but since you would hit an "unavoidable race condition" there is a good chance you will figure out eventually :-)

like image 41
Kasper Munck Avatar answered Nov 14 '22 14:11

Kasper Munck


Normally I'd take @bbum's stance on this, but in the case of NSURLCache disagree.

NSURLConnection is thread safe, in the sense that a given instance can be scheduled on a thread of your choosing (but don't try to schedule a single instance on multiple threads!)

By default, connections all interact with +[NSURLCache sharedCache]. Logically, this means either NSURLCache is itself thread safe, or offers a locking mechanism which clients can explicitly call themselves. Since the latter doesn't exist, I deduce NSURLCache is thread safe.

Would still like this to be documented officially, mind!

like image 4
Mike Abdullah Avatar answered Nov 14 '22 13:11

Mike Abdullah