xrpld
Loading...
Searching...
No Matches
CountedObject.h
1#pragma once
2
3#include <xrpl/beast/type_name.h>
4
5#include <atomic>
6#include <string>
7#include <utility>
8#include <vector>
9
10namespace xrpl {
11
16{
17public:
18 static CountedObjects&
19 getInstance() noexcept;
20
23
24 [[nodiscard]] List
25 getCounts(int minimumThreshold) const;
26
27public:
33 class Counter
34 {
35 public:
36 Counter(std::string name) noexcept : name_(std::move(name)), count_(0)
37 {
38 // Insert ourselves at the front of the lock-free linked list
40 Counter* head = nullptr;
41
42 do
43 {
44 head = instance.head_.load();
45 next_ = head;
46 } while (instance.head_.exchange(this) != head);
47
48 ++instance.count_;
49 }
50
51 ~Counter() noexcept = default;
52
53 int
54 increment() noexcept
55 {
56 return ++count_;
57 }
58
59 int
60 decrement() noexcept
61 {
62 return --count_;
63 }
64
65 [[nodiscard]] int
66 getCount() const noexcept
67 {
68 return count_.load();
69 }
70
71 [[nodiscard]] Counter*
72 getNext() const noexcept
73 {
74 return next_;
75 }
76
77 [[nodiscard]] std::string const&
78 getName() const noexcept
79 {
80 return name_;
81 }
82
83 private:
87 };
88
89private:
90 CountedObjects() noexcept;
91 ~CountedObjects() noexcept = default;
92
93private:
94 std::atomic<int> count_;
95 std::atomic<Counter*> head_;
96};
97
98//------------------------------------------------------------------------------
99
108template <class Object>
110{
111private:
112 static auto&
113 getCounter() noexcept
114 {
116 return kC;
117 }
118
119 CountedObject() noexcept
120 {
121 getCounter().increment();
122 }
123
125 {
126 getCounter().increment();
127 }
128
130 operator=(CountedObject const&) noexcept = default;
131
132public:
133 ~CountedObject() noexcept
134 {
135 getCounter().decrement();
136 }
137
138 friend Object;
139};
140
141} // namespace xrpl
Tracks the number of instances of an object.
CountedObject(CountedObject const &) noexcept
CountedObject & operator=(CountedObject const &) noexcept=default
static auto & getCounter() noexcept
~CountedObject() noexcept
Implementation for CountedObject.
~Counter() noexcept=default
int getCount() const noexcept
std::string const & getName() const noexcept
Counter * getNext() const noexcept
Counter(std::string name) noexcept
List getCounts(int minimumThreshold) const
static CountedObjects & getInstance() noexcept
std::vector< Entry > List
std::atomic< Counter * > head_
std::atomic< int > count_
std::pair< std::string, int > Entry
std::string typeName()
Definition type_name.h:16
STL namespace.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5