2 * Copyright 2015 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.
17 #ifndef FOLLY_THREADCACHEDARENA_H_
18 #define FOLLY_THREADCACHEDARENA_H_
20 #include <type_traits>
22 #include <folly/Arena.h>
23 #include <folly/Likely.h>
24 #include <folly/Synchronized.h>
25 #include <folly/ThreadLocal.h>
30 * Thread-caching arena: allocate memory which gets freed when the arena gets
33 * The arena itself allocates memory using malloc() in blocks of
34 * at least minBlockSize bytes.
36 * For speed, each thread gets its own Arena (see Arena.h); when threads
37 * exit, the Arena gets merged into a "zombie" Arena, which will be deallocated
38 * when the ThreadCachedArena object is destroyed.
40 class ThreadCachedArena {
42 explicit ThreadCachedArena(
43 size_t minBlockSize = SysArena::kDefaultMinBlockSize,
44 size_t maxAlign = SysArena::kDefaultMaxAlign);
46 void* allocate(size_t size) {
47 SysArena* arena = arena_.get();
48 if (UNLIKELY(!arena)) {
49 arena = allocateThreadLocalArena();
52 return arena->allocate(size);
55 void deallocate(void* p) {
59 // Gets the total memory used by the arena
60 size_t totalSize() const;
63 struct ThreadLocalPtrTag {};
65 ThreadCachedArena(const ThreadCachedArena&) = delete;
66 ThreadCachedArena(ThreadCachedArena&&) = delete;
67 ThreadCachedArena& operator=(const ThreadCachedArena&) = delete;
68 ThreadCachedArena& operator=(ThreadCachedArena&&) = delete;
70 SysArena* allocateThreadLocalArena();
72 // Zombify the blocks in arena, saving them for deallocation until
73 // the ThreadCachedArena is destroyed.
74 void zombify(SysArena&& arena);
76 const size_t minBlockSize_;
77 const size_t maxAlign_;
79 ThreadLocalPtr<SysArena, ThreadLocalPtrTag> arena_; // Per-thread arena.
81 // Allocations from threads that are now dead.
82 Synchronized<SysArena> zombies_;
86 struct IsArenaAllocator<ThreadCachedArena> : std::true_type { };
90 #endif /* FOLLY_THREADCACHEDARENA_H_ */