@@ -201,18 +201,31 @@ using MemoryDebugHandler = std::function<void(uint8_t* ptr, int64_t size, const
201201struct DebugState {
202202 void Invoke (uint8_t * ptr, int64_t size, const Status& st) {
203203 std::lock_guard<std::mutex> lock (mutex_);
204- handler_ (ptr, size, st);
204+ if (handler_) {
205+ handler_ (ptr, size, st);
206+ }
205207 }
206208
207209 void SetHandler (MemoryDebugHandler handler) {
208210 std::lock_guard<std::mutex> lock (mutex_);
209211 handler_ = std::move (handler);
210212 }
211213
214+ static DebugState* Instance () {
215+ // Instance is constructed on-demand. If it was a global static variable,
216+ // it could be constructed after being used.
217+ static DebugState instance;
218+ return &instance;
219+ }
220+
212221 private:
222+ DebugState () = default ;
223+
224+ ARROW_DISALLOW_COPY_AND_ASSIGN (DebugState);
225+
213226 std::mutex mutex_;
214227 MemoryDebugHandler handler_;
215- } debug_state ;
228+ };
216229
217230void DebugAbort (uint8_t * ptr, int64_t size, const Status& st) { st.Abort (); }
218231
@@ -235,16 +248,17 @@ bool IsDebugEnabled() {
235248 if (env_value.empty ()) {
236249 return false ;
237250 }
251+ auto debug_state = DebugState::Instance ();
238252 if (env_value == " abort" ) {
239- debug_state. SetHandler (DebugAbort);
253+ debug_state-> SetHandler (DebugAbort);
240254 return true ;
241255 }
242256 if (env_value == " trap" ) {
243- debug_state. SetHandler (DebugTrap);
257+ debug_state-> SetHandler (DebugTrap);
244258 return true ;
245259 }
246260 if (env_value == " warn" ) {
247- debug_state. SetHandler (DebugWarn);
261+ debug_state-> SetHandler (DebugWarn);
248262 return true ;
249263 }
250264 ARROW_LOG (WARNING) << " Invalid value for " << kDebugMemoryEnvVar << " : '" << env_value
@@ -318,7 +332,7 @@ class DebugAllocator {
318332 if (ARROW_PREDICT_FALSE (stored_size != size)) {
319333 auto st = Status::Invalid (" Wrong size on " , context, " : given size = " , size,
320334 " , actual size = " , stored_size);
321- debug_state. Invoke (ptr, size, st);
335+ DebugState::Instance ()-> Invoke (ptr, size, st);
322336 }
323337 }
324338
0 commit comments