         return stub
         }
 
-    static func add(_ stub: RequestStub)
-        {
-        synchronized
-            { stubs.insert(stub, at: 0) }
+    fileprivate static var stubs: [RequestStub]
+        {
+        stubsAccessQueue.sync { _stubs }
+        }
+
+    private static func add(_ stub: RequestStub)
+        {
+        stubsAccessQueue.sync
+            { _stubs.insert(stub, at: 0) }
         }
 
     static func clearAll()
         {
-        Self.requestInitialization.await
+        StubbedNetworkProtocol.afterPendingRequestsStubbed
             {
-            synchronized { stubs = [] }
+            stubsAccessQueue.sync
+                { _stubs = [] }
             }
+        }
+
+    static func synchronized<T>(_ action: () -> T) -> T
+        {
+        objc_sync_enter(NetworkStub.self)
+        defer { objc_sync_exit(NetworkStub.self) }
+        return action()
+        }
+    }
+
+private final class StubbedNetworkProtocol: URLProtocol
+    {
+    private static let stubPropertyKey = "\(NetworkStub.self).stub"
+
+    private static var requestInitialization = Latch(name: "initialization of requests")
+
+    static func afterPendingRequestsStubbed(perform action: () -> Void)
+        {
+        Self.requestInitialization.await(whileLocked: action)
         }
 
     override class func canInit(with request: URLRequest) -> Bool


    override func stopLoading()
        { }

    static func synchronized<T>(_ action: () -> T) -> T
        {
        objc_sync_enter(NetworkStub.self)
        defer { objc_sync_exit(NetworkStub.self) }
        return action()
        }
    }

struct RequestStub


        let body = extractBody(from: request)

        let stubs = NetworkStub.stubs
        guard let stub = stubs.first(where: { $0.matcher.matches(request, withBody: body) }) else
            {
            fatalError(
