@@ -704,19 +704,10 @@ void Environment::RunAndClearNativeImmediates(bool only_refed) {
704704 // exceptions, so we do not need to handle that.
705705 RunAndClearInterrupts ();
706706
707- // It is safe to check .size() first, because there is a causal relationship
708- // between pushes to the threadsafe and this function being called.
709- // For the common case, it's worth checking the size first before establishing
710- // a mutex lock.
711- if (native_immediates_threadsafe_.size () > 0 ) {
712- Mutex::ScopedLock lock (native_immediates_threadsafe_mutex_);
713- native_immediates_.ConcatMove (std::move (native_immediates_threadsafe_));
714- }
715-
716- auto drain_list = [&]() {
707+ auto drain_list = [&](NativeImmediateQueue* queue) {
717708 TryCatchScope try_catch (this );
718709 DebugSealHandleScope seal_handle_scope (isolate ());
719- while (auto head = native_immediates_. Shift ()) {
710+ while (auto head = queue-> Shift ()) {
720711 if (head->is_refed ())
721712 ref_count++;
722713
@@ -734,12 +725,26 @@ void Environment::RunAndClearNativeImmediates(bool only_refed) {
734725 }
735726 return false ;
736727 };
737- while (drain_list ()) {}
728+ while (drain_list (&native_immediates_ )) {}
738729
739730 immediate_info ()->ref_count_dec (ref_count);
740731
741732 if (immediate_info ()->ref_count () == 0 )
742733 ToggleImmediateRef (false );
734+
735+ // It is safe to check .size() first, because there is a causal relationship
736+ // between pushes to the threadsafe immediate list and this function being
737+ // called. For the common case, it's worth checking the size first before
738+ // establishing a mutex lock.
739+ // This is intentionally placed after the `ref_count` handling, because when
740+ // refed threadsafe immediates are created, they are not counted towards the
741+ // count in immediate_info() either.
742+ NativeImmediateQueue threadsafe_immediates;
743+ if (native_immediates_threadsafe_.size () > 0 ) {
744+ Mutex::ScopedLock lock (native_immediates_threadsafe_mutex_);
745+ threadsafe_immediates.ConcatMove (std::move (native_immediates_threadsafe_));
746+ }
747+ while (drain_list (&threadsafe_immediates)) {}
743748}
744749
745750void Environment::RequestInterruptFromV8 () {
0 commit comments