@@ -741,19 +741,10 @@ void Environment::RunAndClearNativeImmediates(bool only_refed) {
741741 // exceptions, so we do not need to handle that.
742742 RunAndClearInterrupts ();
743743
744- // It is safe to check .size() first, because there is a causal relationship
745- // between pushes to the threadsafe and this function being called.
746- // For the common case, it's worth checking the size first before establishing
747- // a mutex lock.
748- if (native_immediates_threadsafe_.size () > 0 ) {
749- Mutex::ScopedLock lock (native_immediates_threadsafe_mutex_);
750- native_immediates_.ConcatMove (std::move (native_immediates_threadsafe_));
751- }
752-
753- auto drain_list = [&]() {
744+ auto drain_list = [&](NativeImmediateQueue* queue) {
754745 TryCatchScope try_catch (this );
755746 DebugSealHandleScope seal_handle_scope (isolate ());
756- while (auto head = native_immediates_. Shift ()) {
747+ while (auto head = queue-> Shift ()) {
757748 if (head->is_refed ())
758749 ref_count++;
759750
@@ -771,12 +762,26 @@ void Environment::RunAndClearNativeImmediates(bool only_refed) {
771762 }
772763 return false ;
773764 };
774- while (drain_list ()) {}
765+ while (drain_list (&native_immediates_ )) {}
775766
776767 immediate_info ()->ref_count_dec (ref_count);
777768
778769 if (immediate_info ()->ref_count () == 0 )
779770 ToggleImmediateRef (false );
771+
772+ // It is safe to check .size() first, because there is a causal relationship
773+ // between pushes to the threadsafe immediate list and this function being
774+ // called. For the common case, it's worth checking the size first before
775+ // establishing a mutex lock.
776+ // This is intentionally placed after the `ref_count` handling, because when
777+ // refed threadsafe immediates are created, they are not counted towards the
778+ // count in immediate_info() either.
779+ NativeImmediateQueue threadsafe_immediates;
780+ if (native_immediates_threadsafe_.size () > 0 ) {
781+ Mutex::ScopedLock lock (native_immediates_threadsafe_mutex_);
782+ threadsafe_immediates.ConcatMove (std::move (native_immediates_threadsafe_));
783+ }
784+ while (drain_list (&threadsafe_immediates)) {}
780785}
781786
782787void Environment::RequestInterruptFromV8 () {
0 commit comments