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
14{
15public:
16 static CountedObjects&
17 getInstance() noexcept;
18
21
22 [[nodiscard]] List
23 getCounts(int minimumThreshold) const;
24
25public:
30 class Counter
31 {
32 public:
33 Counter(std::string name) noexcept : name_(std::move(name)), count_(0)
34 {
35 // Insert ourselves at the front of the lock-free linked list
37 Counter* head = nullptr;
38
39 do
40 {
41 head = instance.head_.load();
42 next_ = head;
43 } while (instance.head_.exchange(this) != head);
44
45 ++instance.count_;
46 }
47
48 ~Counter() noexcept = default;
49
50 int
51 increment() noexcept
52 {
53 return ++count_;
54 }
55
56 int
57 decrement() noexcept
58 {
59 return --count_;
60 }
61
62 [[nodiscard]] int
63 getCount() const noexcept
64 {
65 return count_.load();
66 }
67
68 [[nodiscard]] Counter*
69 getNext() const noexcept
70 {
71 return next_;
72 }
73
74 [[nodiscard]] std::string const&
75 getName() const noexcept
76 {
77 return name_;
78 }
79
80 private:
84 };
85
86private:
87 CountedObjects() noexcept;
88 ~CountedObjects() noexcept = default;
89
90private:
91 std::atomic<int> count_;
92 std::atomic<Counter*> head_;
93};
94
95//------------------------------------------------------------------------------
96
104template <class Object>
106{
107private:
108 static auto&
109 getCounter() noexcept
110 {
112 return kC;
113 }
114
115 CountedObject() noexcept
116 {
117 getCounter().increment();
118 }
119
121 {
122 getCounter().increment();
123 }
124
126 operator=(CountedObject const&) noexcept = default;
127
128public:
129 ~CountedObject() noexcept
130 {
131 getCounter().decrement();
132 }
133
134 friend Object;
135};
136
137} // 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