Log (de)compression bytes
[folly.git] / folly / executors / IOObjectCache.h
1 /*
2  * Copyright 2017-present Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <folly/ThreadLocal.h>
20 #include <folly/executors/GlobalExecutor.h>
21 #include <folly/io/async/EventBase.h>
22
23 namespace folly {
24
25 /*
26  * IOObjectCache manages objects of type T that are dependent on an EventBase
27  * provided by the global IOExecutor.
28  *
29  * Provide a factory that creates T objects given an EventBase, and get() will
30  * lazily create T objects based on an EventBase from the global IOExecutor.
31  * These are stored thread locally - for a given pair of event base and calling
32  * thread there will only be one T object created.
33  *
34  * The primary use case is for managing objects that need to do async IO on an
35  * event base (e.g. thrift clients) that can be used outside the IO thread
36  * without much hassle. For instance, you could use this to manage Thrift
37  * clients that are only ever called from within other threads without the
38  * calling thread needing to know anything about the IO threads that the clients
39  * will do their work on.
40  */
41 template <class T>
42 class IOObjectCache {
43  public:
44   typedef std::function<std::shared_ptr<T>(folly::EventBase*)> TFactory;
45
46   IOObjectCache() = default;
47   explicit IOObjectCache(TFactory factory) : factory_(std::move(factory)) {}
48
49   std::shared_ptr<T> get() {
50     CHECK(factory_);
51     auto eb = getIOExecutor()->getEventBase();
52     CHECK(eb);
53     auto it = cache_->find(eb);
54     if (it == cache_->end()) {
55       auto p = cache_->insert(std::make_pair(eb, factory_(eb)));
56       it = p.first;
57     }
58     return it->second;
59   };
60
61   void setFactory(TFactory factory) {
62     factory_ = std::move(factory);
63   }
64
65  private:
66   folly::ThreadLocal<std::map<folly::EventBase*, std::shared_ptr<T>>> cache_;
67   TFactory factory_;
68 };
69
70 } // namespace folly