@@ -211,39 +211,31 @@ SorobanMetrics::accumulateLedgerWriteByte(uint64_t writeByte)
211211SorobanMetrics::ApplyMetricsBatch&
212212SorobanMetrics::getApplyThreadBatch ()
213213{
214- // One entry per (thread, SorobanMetrics instance): tests can run several
215- // applications in one process and threads outlive applications, so the
216- // weak_ptr is re-validated on every first-use (the registry owns the
217- // batches; a stale entry from a destroyed instance whose address got
218- // reused expires together with its registry).
219- static thread_local std::unordered_map<SorobanMetrics const *,
220- std::weak_ptr<ApplyMetricsBatch>>
221- tlBatches;
222- auto & weak = tlBatches[this ];
223- if (auto existing = weak.lock ())
214+ std::lock_guard<std::mutex> lock (mApplyBatchesMutex );
215+ auto [it, inserted] = mApplyBatches .try_emplace (std::this_thread::get_id ());
216+ if (inserted)
224217 {
225- return *existing ;
218+ it-> second = std::make_unique<ApplyMetricsBatch>() ;
226219 }
227- auto batch = std::make_shared<ApplyMetricsBatch>();
228- {
229- std::lock_guard<std::mutex> lock (mApplyBatchesMutex );
230- mApplyBatches .push_back (batch);
231- }
232- weak = batch;
233- return *batch;
220+ return *it->second ;
234221}
235222
236223void
237224SorobanMetrics::flushApplyMetricsBatches ()
238225{
239- std::vector<std::shared_ptr <ApplyMetricsBatch>> batches;
226+ std::vector<std::unique_ptr <ApplyMetricsBatch>> batches;
240227 {
241228 std::lock_guard<std::mutex> lock (mApplyBatchesMutex );
242- batches = mApplyBatches ;
243- }
244- if (batches.empty ())
245- {
246- return ;
229+ if (mApplyBatches .empty ())
230+ {
231+ return ;
232+ }
233+ batches.reserve (mApplyBatches .size ());
234+ for (auto & [_, v] : mApplyBatches )
235+ {
236+ batches.emplace_back (std::move (v));
237+ }
238+ mApplyBatches .clear ();
247239 }
248240
249241 ApplyMetricsBatch total;
0 commit comments