proxygen
IOObjectCache.h
Go to the documentation of this file.
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 <map>
20 
21 #include <folly/ThreadLocal.h>
24 
25 namespace folly {
26 
27 /*
28  * IOObjectCache manages objects of type T that are dependent on an EventBase
29  * provided by the global IOExecutor.
30  *
31  * Provide a factory that creates T objects given an EventBase, and get() will
32  * lazily create T objects based on an EventBase from the global IOExecutor.
33  * These are stored thread locally - for a given pair of event base and calling
34  * thread there will only be one T object created.
35  *
36  * The primary use case is for managing objects that need to do async IO on an
37  * event base (e.g. thrift clients) that can be used outside the IO thread
38  * without much hassle. For instance, you could use this to manage Thrift
39  * clients that are only ever called from within other threads without the
40  * calling thread needing to know anything about the IO threads that the clients
41  * will do their work on.
42  */
43 template <class T>
45  public:
46  typedef std::function<std::shared_ptr<T>(folly::EventBase*)> TFactory;
47 
48  IOObjectCache() = default;
49  explicit IOObjectCache(TFactory factory) : factory_(std::move(factory)) {}
50 
51  std::shared_ptr<T> get() {
52  CHECK(factory_);
53  auto eb = getIOExecutor()->getEventBase();
54  CHECK(eb);
55  auto it = cache_->find(eb);
56  if (it == cache_->end()) {
57  auto p = cache_->insert(std::make_pair(eb, factory_(eb)));
58  it = p.first;
59  }
60  return it->second;
61  };
62 
63  void setFactory(TFactory factory) {
64  factory_ = std::move(factory);
65  }
66 
67  private:
70 };
71 
72 } // namespace folly
folly::ThreadLocal< std::map< folly::EventBase *, std::shared_ptr< T > > > cache_
Definition: IOObjectCache.h:68
IOObjectCache(TFactory factory)
Definition: IOObjectCache.h:49
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
STL namespace.
—— Concurrent Priority Queue Implementation ——
Definition: AtomicBitSet.h:29
std::function< std::shared_ptr< T >folly::EventBase *)> TFactory
Definition: IOObjectCache.h:46
void setFactory(TFactory factory)
Definition: IOObjectCache.h:63
std::shared_ptr< IOExecutor > getIOExecutor()