------------------------------------------------------ thread factories
336786
@Process(actionType = AddThreadFactory.class)
    public void addThreadFactory(final AddThreadFactory action, final Channel channel) {
        operationDelegate.onCreateResource(THREAD_FACTORY_ADDRESS,
                action.getProperty().getName(), action.getProperty().getValue(),
                new ChannelCallback(statementContext, channel));
    }
1174344
def join(self):
        """"""
        for thread in self.worker_threads:
            thread.join()
        WorkerThread.join(self)
211828
@Override
    public void registerFactories(ChannelFactoryProvider provider) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            Tr.event(tc, "Register factory provider; " + provider.getClass().getName());
        }
        synchronized (this.factories) {
            for (Entry<String, Class<? extends ChannelFactory>> entry : provider.getTypes().entrySet()) {
                this.providers.put(entry.getKey(), provider);
                Class<? extends ChannelFactory> newFactory = entry.getValue();
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Class<? extends ChannelFactory> prevFactory = this.factories.get(entry.getKey());
                    if (null != prevFactory && newFactory != prevFactory) {
                        Tr.event(tc, "WARNING: overlaying existing factory: " + prevFactory);
                    }
                }
                this.factories.put(entry.getKey(), newFactory);
            }
        } // end-sync

        // now that we have a new factory type, tell ChannelUtils to process
        // any delayed config that might be waiting for it
        ChannelUtils.loadConfig(null);
    }
451370
public Thread newThread(Runnable r) {
        return factory == this ? new Thread(r)
                               : factory.newThread(r);
    }
719876
private synchronized void createExecutor() {
        if (componentConfig == null) {
            // this is a completely normal occurrence and can happen if a ThreadFactory is bound prior to
            // component activation...  the proper thing to do is to do nothing and wait for activation
            return;
        }

        if (threadPoolController != null)
            threadPoolController.deactivate();

        ThreadPoolExecutor oldPool = threadPool;

        poolName = (String) componentConfig.get("name");
        String threadGroupName = poolName + " Thread Group";

        int coreThreads = Integer.parseInt(String.valueOf(componentConfig.get("coreThreads")));
        int maxThreads = Integer.parseInt(String.valueOf(componentConfig.get("maxThreads")));

        if (maxThreads <= 0) {
            maxThreads = Integer.MAX_VALUE;
        }

        if (coreThreads < 0) {
            coreThreads = 2 * CpuInfo.getAvailableProcessors();
        }

        // Make sure coreThreads is not bigger than maxThreads, subject to MINIMUM_POOL_SIZE limit
        coreThreads = Math.max(MINIMUM_POOL_SIZE, Math.min(coreThreads, maxThreads));
        // ... and then make sure maxThreads is not smaller than coreThreads ...
        maxThreads = Math.max(coreThreads, maxThreads);

        BlockingQueue<Runnable> workQueue = new BoundedBuffer<Runnable>(java.lang.Runnable.class, 1000, 1000);

        RejectedExecutionHandler rejectedExecutionHandler = new ExpandPolicy(workQueue, this);

        threadPool = new ThreadPoolExecutor(coreThreads, maxThreads, 0, TimeUnit.MILLISECONDS, workQueue, threadFactory != null ? threadFactory : new ThreadFactoryImpl(poolName, threadGroupName), rejectedExecutionHandler);

        threadPoolController = new ThreadPoolController(this, threadPool);

        if (oldPool != null) {
            softShutdown(oldPool);
        }
    }
286902
static final void eraseThreadLocals(Thread thread) {
    U.putObject(thread, THREADLOCALS, null);
    U.putObject(thread, INHERITABLETHREADLOCALS, null);
  }
263360
public final Factory registerFactory(Factory factory) {
        if (factory == null) {
            throw new NullPointerException();
        }
        try {
            factoryLock.acquireWrite();
            factories.add(0, factory);
            clearCaches();
        }
        finally {
            factoryLock.releaseWrite();
        }
        notifyChanged();
        return factory;
    }
1183878
@Nullable
    public static ForkJoinWorkerThreadFactory unwrap(@Nullable ForkJoinWorkerThreadFactory threadFactory) {
        if (!isDisableInheritableForkJoinWorkerThreadFactory(threadFactory)) return threadFactory;

        return ((DisableInheritableForkJoinWorkerThreadFactoryWrapper) threadFactory).unwrap();
    }
1267351
private static ThreadFactory createThreadFactory(ThreadFactory threadFactory, String threadNamePrefix,
			Boolean daemon) {
		if (threadFactory != null) {
			return threadFactory;
		}

		if (threadNamePrefix != null) {
			if (daemon != null) {
				return ThreadPoolUtil.buildThreadFactory(threadNamePrefix, daemon);
			} else {
				return ThreadPoolUtil.buildThreadFactory(threadNamePrefix);
			}
		}

		return Executors.defaultThreadFactory();
	}
678874
function(eventName, cpuNumber, pid, ts, eventBase) {
      var event = kswapdWakeRE.exec(eventBase.details);
      if (!event)
        return false;

      var tgid = parseInt(eventBase.tgid);

      var nid = parseInt(event[1]);
      var order = parseInt(event[2]);

      var kthread = this.importer.getOrCreateKernelThread(
          eventBase.threadName, tgid, pid);

      if (kthread.openSliceTS) {
        if (order > kthread.order) {
          kthread.order = order;
        }
      } else {
        kthread.openSliceTS = ts;
        kthread.order = order;
      }
      return true;
    }
91983
@SuppressWarnings("unchecked")
    @PostConstruct
    void init(BeanContext beanContext, ThreadFactory threadFactory) {
        try {
            BeanDefinition<ExecutorService> beanDefinition = beanContext.getBeanDefinition(ExecutorService.class, Qualifiers.byName(TaskExecutors.SCHEDULED));
            Collection<BeanCreatedEventListener> schedulerCreateListeners =
                    beanContext.getBeansOfType(BeanCreatedEventListener.class, Qualifiers.byTypeArguments(ScheduledExecutorService.class));

            Schedulers.addExecutorServiceDecorator(Environment.MICRONAUT, (scheduler, scheduledExecutorService) -> {
                for (BeanCreatedEventListener schedulerCreateListener : schedulerCreateListeners) {
                    Object newBean = schedulerCreateListener.onCreated(new BeanCreatedEvent(beanContext, beanDefinition, BeanIdentifier.of("reactor-" + scheduler.getClass().getSimpleName()), scheduledExecutorService));
                    if (!(newBean instanceof ScheduledExecutorService)) {
                        throw new BeanContextException("Bean creation listener [" + schedulerCreateListener + "] should return ScheduledExecutorService, but returned " + newBean);
                    }
                    scheduledExecutorService = (ScheduledExecutorService) newBean;
                }
                return scheduledExecutorService;
            });
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not instrument Reactor for Tracing: " + e.getMessage(), e);
            }
        }
    }
119806
private void joinAllThreads() {
        Iterator iter = registeredWachdogs.values().iterator();
        while (iter.hasNext()) {
            Watchdog th = (Watchdog) iter.next();
            boolean isJoining = true;
            if (!th.isAlive() && log.isDebugEnabled()) {
                log.debug("Thread " + th + " finished");
            }
            while (th.isAlive() && isJoining) {
                try {
                    th.getThread().join();
                    isJoining = false;
                    if (log.isDebugEnabled()) {
                        log.debug("Thread " + th + " joined and finished");
                    }
                } catch (InterruptedException e) {
                }
            }
        }
    }
1106792
void compile() {
    TypeInfo factoryType = innerClasses.registerInnerClass(FACTORY_CLASS, FACTORY_ACCESS);
    SoyClassWriter cw =
        SoyClassWriter.builder(factoryType)
            .implementing(FACTORY_TYPE)
            .setAccess(FACTORY_ACCESS)
            .sourceFileName(templateNode.getSourceLocation().getFileName())
            .build();
    innerClasses.registerAsInnerClass(cw, factoryType);

    generateStaticInitializer(cw);
    defineDefaultConstructor(cw, factoryType);
    generateCreateMethod(cw, factoryType);
    cw.visitEnd();
    innerClasses.add(cw.toClassData());
  }
452317
@Override
    public void launch(@NonNull ThreadingModel threading) {
        this.threadingModel = threading;

        switch (threading) {
            case SINGLE_THREAD: {

                log.warn("SINGLE_THREAD model is used, performance will be significantly reduced");

                // single thread for all queues. shouldn't be used in real world
                threadA = new Thread(() -> {
                    while (runner.get()) {
                        if (subscriptionForShards != null)
                            subscriptionForShards.poll(messageHandlerForShards, 512);

                        idler.idle(subscriptionForClients.poll(messageHandlerForClients, 512));
                    }
                });

                threadA.setDaemon(true);
                threadA.start();
                }
                break;
            case DEDICATED_THREADS: {
                // we start separate thread for each handler

                /**
                 * We definitely might use less conditional code here, BUT i'll keep it as is,
                 * only because we want code to be obvious for people
                 */
                final AtomicBoolean localRunner = new AtomicBoolean(false);
                if (nodeRole == NodeRole.NONE) {
                    throw new ND4JIllegalStateException("No role is set for current node!");
                } else if (nodeRole == NodeRole.SHARD || nodeRole == NodeRole.BACKUP || nodeRole == NodeRole.MASTER) {
                    // // Shard or Backup uses two subscriptions

                    // setting up thread for shard->client communication listener
                    if (messageHandlerForShards != null) {
                        threadB = new Thread(() -> {
                            while (runner.get())
                                idler.idle(subscriptionForShards.poll(messageHandlerForShards, 512));

                        });
                        threadB.setDaemon(true);
                        threadB.setName("VoidParamServer subscription threadB [" + nodeRole + "]");
                    }

                    // setting up thread for inter-shard communication listener
                    threadA = new Thread(() -> {
                        localRunner.set(true);
                        while (runner.get())
                            idler.idle(subscriptionForClients.poll(messageHandlerForClients, 512));
                    });

                    if (threadB != null) {
                        Nd4j.getAffinityManager().attachThreadToDevice(threadB,
                                        Nd4j.getAffinityManager().getDeviceForCurrentThread());
                        threadB.setDaemon(true);
                        threadB.setName("VoidParamServer subscription threadB [" + nodeRole + "]");
                        threadB.start();
                    }
                } else {
                    // setting up thread for shard->client communication listener
                    threadA = new Thread(() -> {
                        localRunner.set(true);
                        while (runner.get())
                            idler.idle(subscriptionForClients.poll(messageHandlerForClients, 512));
                    });
                }

                // all roles have threadA anyway
                Nd4j.getAffinityManager().attachThreadToDevice(threadA,
                                Nd4j.getAffinityManager().getDeviceForCurrentThread());
                threadA.setDaemon(true);
                threadA.setName("VoidParamServer subscription threadA [" + nodeRole + "]");
                threadA.start();

                while (!localRunner.get())
                    try {
                        Thread.sleep(50);
                    } catch (Exception e) {
                    }
            }
                break;
            case SAME_THREAD: {
                // no additional threads at all, we do poll within takeMessage loop
                log.warn("SAME_THREAD model is used, performance will be dramatically reduced");
            }
                break;
            default:
                throw new IllegalStateException("Unknown thread model: [" + threading.toString() + "]");
        }
    }
1252766
synchronized private void startFrameThreads() {
    if(!process)
      return;
    int requests = unassignedEncodeRequests.size();
    int frames = inactiveFrameThreads.size();
    frames = (requests <= frames) ? requests:frames;
    for(int i = 0; i < frames; i++) {
      FrameThread ft = inactiveFrameThreads.remove(0);
      Thread thread = new Thread(ft);
      frameThreadMap.put(ft, thread);
      thread.start();
    }
  }
345263
@Nullable
    public static ThreadFactory unwrap(@Nullable ThreadFactory threadFactory) {
        if (!isDisableInheritableThreadFactory(threadFactory)) return threadFactory;

        return ((DisableInheritableThreadFactory) threadFactory).unwrap();
    }
1295960
private void ensureWatchThreadRunning() {
		if (!threadRunning) {
			thread = new Thread(watchThread);
			thread.setDaemon(true);
			thread.start();
			watchThread.setThread(thread);
			watchThread.updateName();
			threadRunning = true;
		}
	}