We're guaranteed that only one thread will be called with this method at any time
493550
protected void process(Collection<R> requests) {
        for(;;) {
            while(!requests.isEmpty()) {
                removeAndProcess(requests); // remove matching requests and process them
            }
            lock.lock();
            try {
                if(requests.isEmpty()) {
                    setProcessing(false);
                    return;
                }
            }
            finally {
                lock.unlock();
            }
        }
    }
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);
        }
    }
646288
public void purgeThreadLocal() {
        // if thread local pools exist, check to see if we have one created and
        // therefore need to tell it to purge
        if (null != threadLocals) {
            LocalThreadObjectPool pool = threadLocals.get();
            if (null != pool) {
                Object[] data = pool.purge();
                if (0 < data.length) {
                    mainPool.putBatch(data);
                }
            }
        }
    }
1324395
public void init() {
        if (executorService == null) {
            int numThreads = Math.min(Math.max(Runtime.getRuntime().availableProcessors(), 1), 4);
            executorService = Executors.newFixedThreadPool(numThreads);
            myOwnExecutorService = true;
        } else {
            myOwnExecutorService = false;
        }
    }
572789
def try_lock
      locked = false
      Thread.exclusive do
        clean
        unless(locked?(false))
          do_lock
          locked = true
        else
          locked = owner?(Thread.current)
        end
      end
      locked
    end
745129
def close_thread(self):
		
		if self.__thread is not None and self.__thread.is_alive() is True:
			raise WThreadJoiningTimeoutError('Thread is still alive. Thread name: %s' % self.__thread.name)
		self.start_event().clear()
		self.__thread = None
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() + "]");
        }
    }
995198
def get_selected_thread(self):
        """"""
        threadlinewidget = self.get_selected_threadline()
        thread = None
        if threadlinewidget:
            thread = threadlinewidget.get_thread()
        return thread
1125204
private static <T> Callable<T> threadRenaming(final String name, final Callable<T> callable) {
    checkNotNull(name);
    checkNotNull(callable);
    return new Callable<T>() {
      @Override public T call() throws Exception {
        Thread currentThread = Thread.currentThread();
        String oldName = currentThread.getName();
        currentThread.setName(name);
        try {
          return callable.call();
        } finally {
          currentThread.setName(oldName);
        }
      }
    };
  }
1173998
private void doInterruptAllWaitingThreads() {
    	//Interrupt all the threads
    	for (int i=0; i<nThreads; i++) {
    		threads[i].interrupt();
    	}
    	
    	synchronized(lock) {
    		lock.notify();
    	}
    }
87761
public void lock() {
		if (cancel != null)
			return;
		if (error != null)
			return;
		Thread t;
		BlockedThreadHandler blockedHandler;
		do {
			synchronized (this) {
				if (!locked) {
					locked = true;
					return;
				}
				t = Thread.currentThread();
				blockedHandler = Threading.getBlockedThreadHandler(t);
				if (blockedHandler != null) break;
				try { this.wait(0); }
				catch (InterruptedException e) { continue; }
			}
		} while (true);
		blockedHandler.blocked(this, 0);
	}
1015719
private synchronized void getThreadLock() {
		while (sessionId == null && curUsedThread > 1) {
			try {
				Debug.logVerbose("No session. Only one thread is authorized. Waiting ...", module);
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		while (curUsedThread >= maxThreadCount) {
			try {
				Debug.logVerbose("[JdonFramework]Max concurent http call reached. Waiting ...", module);
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		curUsedThread++;
	}
634836
@Override
    public void free() {
        try {
        if(hasCoreConnection()) {
            this.getCoreConnection().close();
        }
        this.fireConnectionFreed();
        this.boundThreadId= Thread.currentThread().getId();

    } finally {
        this.setClosed(true);
        // state may be important for State-Listener, so its set after the listener did their work
        setTransactionalData(false);

        // re-opem is not possible
        // this.connection=null;
        this.releaseThreadBinding();
    }

    }
534287
protected void startThreadIfNeeded() {
        // create and start thread if one doesn't exist
        while (executor.get() == null || ! executor.get().isInitialized()) {
            if (executor.compareAndSet(null, new ScheduledExecutor())) {
                // initialize the executor that we 'won' setting
                executor.get().initialize();
            }
        }
    }
194358
public void releaseExclusiveLock() throws NoExclusiveLockException
  {
    if (tc.isEntryEnabled()) Tr.entry(tc, "releaseExclusiveLock",this);

    Thread currentThread = Thread.currentThread();

    synchronized(this)
    {
      if ((_threadHoldingExclusiveLock == null) || (!_threadHoldingExclusiveLock.equals(currentThread)))
      {
        if (tc.isEntryEnabled()) Tr.exit(tc, "releaseExclusiveLock", "NoExclusiveLockException");
        throw new NoExclusiveLockException();
      }

      _threadHoldingExclusiveLock = null;
      _threadRequestingExclusiveLock = null;

      // There may be thread waiting for the exclusive lock to be released. Notify them of this event.
      this.notifyAll();
    }

    if (tc.isEntryEnabled()) Tr.exit(tc, "releaseExclusiveLock");
  }
24153
static WeakReference<Thread> currentThreadRef() {
        WeakReference<Thread> ref = weakThread.get();
        if (ref == null) {
            ref = new WeakReference<>(Thread.currentThread());
            weakThread.set(ref);
        }
        return ref;
    }
230604
public void onChildThreadLaunchBegin()
  {
    _threadCount.incrementAndGet();
    
    int startCount = _startingCount.decrementAndGet();

    if (startCount < 0) {
      _startingCount.set(0);
      
      new IllegalStateException().printStackTrace();
    }

    _createCountTotal.incrementAndGet();
    
    wakeIfLowIdle();
  }