2 * Copyright 2017-present Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <folly/ThreadLocal.h>
20 #include <folly/executors/GlobalExecutor.h>
21 #include <folly/io/async/EventBase.h>
26 * IOObjectCache manages objects of type T that are dependent on an EventBase
27 * provided by the global IOExecutor.
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.
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.
44 typedef std::function<std::shared_ptr<T>(folly::EventBase*)> TFactory;
46 IOObjectCache() = default;
47 explicit IOObjectCache(TFactory factory) : factory_(std::move(factory)) {}
49 std::shared_ptr<T> get() {
51 auto eb = getIOExecutor()->getEventBase();
53 auto it = cache_->find(eb);
54 if (it == cache_->end()) {
55 auto p = cache_->insert(std::make_pair(eb, factory_(eb)));
61 void setFactory(TFactory factory) {
62 factory_ = std::move(factory);
66 folly::ThreadLocal<std::map<folly::EventBase*, std::shared_ptr<T>>> cache_;