(ns metabase.async.streaming-response.thread-pool
  (:require
   [metabase.config :as config])
  (:import
   (java.util.concurrent Executors ThreadPoolExecutor)
   (org.apache.commons.lang3.concurrent BasicThreadFactory$Builder)))
(set! *warn-on-reflection* true)
(def ^:private ^Long thread-pool-max-size
  (or (config/config-int :mb-async-query-thread-pool-size)
      (config/config-int :mb-jetty-maxthreads)
      50))
(defonce ^:private thread-pool*
  (delay
    (Executors/newFixedThreadPool thread-pool-max-size
                                  (.build
                                   (doto (BasicThreadFactory$Builder.)
                                     (.namingPattern "streaming-response-thread-pool-%d")
                                     ;; Daemon threads do not block shutdown of the JVM
                                     (.daemon true))))))

Thread pool for asynchronously running streaming responses.

(defn thread-pool
  ^ThreadPoolExecutor []
  @thread-pool*)

The number of active streaming response threads.

(defn active-thread-count
  []
  (.getActiveCount (thread-pool)))

The number of queued streaming response threads.

(defn queued-thread-count
  []
  (count (.getQueue (thread-pool))))