@@ -460,15 +460,16 @@ void Environment::InitializeLibuv(bool start_profiler_idle_notifier) {
460460 uv_check_init (event_loop (), &idle_check_handle_);
461461 uv_async_init (
462462 event_loop (),
463- &cleanup_finalization_groups_async_ ,
463+ &task_queues_async_ ,
464464 [](uv_async_t * async) {
465465 Environment* env = ContainerOf (
466- &Environment::cleanup_finalization_groups_async_ , async);
466+ &Environment::task_queues_async_ , async);
467467 env->CleanupFinalizationGroups ();
468+ env->RunAndClearNativeImmediates ();
468469 });
469470 uv_unref (reinterpret_cast <uv_handle_t *>(&idle_prepare_handle_));
470471 uv_unref (reinterpret_cast <uv_handle_t *>(&idle_check_handle_));
471- uv_unref (reinterpret_cast <uv_handle_t *>(&cleanup_finalization_groups_async_ ));
472+ uv_unref (reinterpret_cast <uv_handle_t *>(&task_queues_async_ ));
472473
473474 thread_stopper ()->Install (
474475 this , static_cast <void *>(this ), [](uv_async_t * handle) {
@@ -532,7 +533,7 @@ void Environment::RegisterHandleCleanups() {
532533 close_and_finish,
533534 nullptr );
534535 RegisterHandleCleanup (
535- reinterpret_cast <uv_handle_t *>(&cleanup_finalization_groups_async_ ),
536+ reinterpret_cast <uv_handle_t *>(&task_queues_async_ ),
536537 close_and_finish,
537538 nullptr );
538539}
@@ -663,6 +664,15 @@ void Environment::RunAndClearNativeImmediates(bool only_refed) {
663664 " RunAndClearNativeImmediates" , this );
664665 size_t ref_count = 0 ;
665666
667+ // It is safe to check .size() first, because there is a causal relationship
668+ // between pushes to the threadsafe and this function being called.
669+ // For the common case, it's worth checking the size first before establishing
670+ // a mutex lock.
671+ if (native_immediates_threadsafe_.size () > 0 ) {
672+ Mutex::ScopedLock lock (native_immediates_threadsafe_mutex_);
673+ native_immediates_.ConcatMove (std::move (native_immediates_threadsafe_));
674+ }
675+
666676 NativeImmediateQueue queue;
667677 queue.ConcatMove (std::move (native_immediates_));
668678
@@ -1084,7 +1094,7 @@ void Environment::CleanupFinalizationGroups() {
10841094 if (try_catch.HasCaught () && !try_catch.HasTerminated ())
10851095 errors::TriggerUncaughtException (isolate (), try_catch);
10861096 // Re-schedule the execution of the remainder of the queue.
1087- uv_async_send (&cleanup_finalization_groups_async_ );
1097+ uv_async_send (&task_queues_async_ );
10881098 return ;
10891099 }
10901100 }
0 commit comments