Factory to make a threadsafe version of CIHM. This is used
exclusively by some internal CI adapters that don't have
the natural thread-safety protocol/design of VoltNetwork.
348826
public static ClientInterfaceHandleManager makeThreadSafeCIHM(
            boolean isAdmin, Connection connection, ClientInterfaceRepairCallback callback, AdmissionControlGroup acg)
    {
        return new ClientInterfaceHandleManager(isAdmin, connection, callback, acg) {
            @Override
            synchronized long getHandle(boolean isSinglePartition, int partitionId,
                    long clientHandle, int messageSize, long creationTimeNanos, String procName, long initiatorHSId,
                    boolean isShortCircuitRead) {
                return super.getHandle(isSinglePartition, partitionId,
                        clientHandle, messageSize, creationTimeNanos, procName, initiatorHSId, isShortCircuitRead);
            }
            @Override
            synchronized Iv2InFlight findHandle(long ciHandle) {
                return super.findHandle(ciHandle);
            }
            @Override
            synchronized Iv2InFlight removeHandle(long ciHandle) {
                return super.removeHandle(ciHandle);
            }
            @Override
            synchronized long getOutstandingTxns() {
                return super.getOutstandingTxns();
            }
            @Override
            synchronized void freeOutstandingTxns() {
                super.freeOutstandingTxns();
            }

            @Override
            synchronized List<Iv2InFlight> removeHandlesForPartitionAndInitiator(Integer partitionId,
                    Long initiatorHSId) {
                return super.removeHandlesForPartitionAndInitiator(partitionId, initiatorHSId);
            }

            @Override
            synchronized boolean shouldCheckThreadIdAssertion()
            {
                return false;
            }
        };
    }
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);
        }
    }
25815
def enable_thread_safety(self):
        
        if self.threadsafe:
            return                        # Already done!
        if self._running.isSet():
            raise RuntimeError('Cannot enable thread safety after start')

        def _getattr(obj, name):
            # use 'is True' so mock objects don't return true for everything
            return getattr(obj, name, False) is True

        for name in dir(self):
            try:
                meth = getattr(self, name)
            except AttributeError:
                # Subclasses may have computed attributes that don't work
                # before they are started, so let's ignore those
                pass
            if not callable(meth):
                continue
            make_threadsafe = _getattr(meth, 'make_threadsafe')
            make_threadsafe_blocking = _getattr(meth, 'make_threadsafe_blocking')

            if make_threadsafe:
                assert not make_threadsafe_blocking
                meth = self._make_threadsafe(meth)
                setattr(self, name, meth)
            elif make_threadsafe_blocking:
                meth = self._make_threadsafe_blocking(meth)
                setattr(self, name, meth)

        self._threadsafe = True
68049
public SolrTransactionSynchronizationAdapter withDefaultBehaviour() {

		this.adapter.registerCompletionDelegate(TransactionSynchronization.STATUS_COMMITTED,
				new SolrTransactionSynchronizationAdapter.CommitTransaction(this.collectionName));
		this.adapter.registerCompletionDelegate(TransactionSynchronization.STATUS_ROLLED_BACK,
				new SolrTransactionSynchronizationAdapter.RollbackTransaction(this.collectionName));

		return this.adapter;
	}
848615
public static SMTPClientTransportFactory createNio(int workerCount) {
        return new NettySMTPClientTransportFactory(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), workerCount), FACTORY);
    }
682632
public void createNetworkAdapter(VirtualNetworkAdapterType type, String networkName, String macAddress, boolean wakeOnLan, boolean startConnected) throws InvalidProperty, RuntimeFault, RemoteException, InterruptedException {
        VirtualMachinePowerState powerState = vm.getRuntime().getPowerState();
        String vmVerStr = vm.getConfig().getVersion();
        int vmVer = Integer.parseInt(vmVerStr.substring(vmVerStr.length() - 2));

        if ((powerState == VirtualMachinePowerState.suspended)) {
            throw new InvalidPowerState();
        }

        HostSystem host = new HostSystem(vm.getServerConnection(), vm.getRuntime().getHost());
        ComputeResource cr = (ComputeResource) host.getParent();
        EnvironmentBrowser envBrowser = cr.getEnvironmentBrowser();
        ConfigTarget configTarget = envBrowser.queryConfigTarget(host);
        VirtualMachineConfigOption vmCfgOpt = envBrowser.queryConfigOption(null, host);

        type = validateNicType(vmCfgOpt.getGuestOSDescriptor(), vm.getConfig().getGuestId(), type);

        VirtualDeviceConfigSpec nicSpec = createNicSpec(type, networkName, macAddress, wakeOnLan, startConnected, configTarget);

        VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
        vmConfigSpec.setDeviceChange(new VirtualDeviceConfigSpec[]{nicSpec});
        Task task = vm.reconfigVM_Task(vmConfigSpec);

        task.waitForTask(200, 100);
    }
795261
public static ThreadFactory buildThreadFactory(@NotNull String threadNamePrefix, @NotNull boolean daemon) {
		return new ThreadFactoryBuilder().setNameFormat(threadNamePrefix + "-%d").setDaemon(daemon).build();
	}
345263
@Nullable
    public static ThreadFactory unwrap(@Nullable ThreadFactory threadFactory) {
        if (!isDisableInheritableThreadFactory(threadFactory)) return threadFactory;

        return ((DisableInheritableThreadFactory) threadFactory).unwrap();
    }
1128048
public static ThreadFactory namedThreads(String pattern, Logger log) {
    return new ThreadFactoryBuilder()
        .setNameFormat(pattern)
        .setThreadFactory(new AtomixThreadFactory())
        .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
        .build();
  }
1033463
@FFDCIgnore(value = { Throwable.class })
    // Liberty Change for CXF End
    protected static Object createProvider(String className, Bus bus) {

        try {
            Class<?> cls = ClassLoaderUtils.loadClass(className, ProviderFactory.class);
            for (Constructor<?> c : cls.getConstructors()) {
                if (c.getParameterTypes().length == 1 && c.getParameterTypes()[0] == Bus.class) {
                    return c.newInstance(bus);
                }
            }
            return cls.newInstance();
        } catch (Throwable ex) {
            String message = "Problem with creating the default provider " + className;
            if (ex.getMessage() != null) {
                message += ": " + ex.getMessage();
            } else {
                message += ", exception class : " + ex.getClass().getName();
            }
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, message);
            }
        }
        return null;
    }
1331456
private static ThreadFactory build(String format) {
        return new ThreadFactory() {
            AtomicInteger counter = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r, String.format(format, counter.getAndAdd(1)));
                thread.setDaemon(true);
                return thread;
            }
        };
    }
646945
@Nullable
    public static ForkJoinWorkerThreadFactory getDisableInheritableForkJoinWorkerThreadFactory(@Nullable ForkJoinWorkerThreadFactory threadFactory) {
        if (threadFactory == null || isDisableInheritableForkJoinWorkerThreadFactory(threadFactory))
            return threadFactory;

        return new DisableInheritableForkJoinWorkerThreadFactoryWrapper(threadFactory);
    }
877894
private synchronized VirtualConnectionFactory getOutboundVCFactory(List<OutboundChannelDefinition> channelDefs) throws ChannelFrameworkException {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "getOutboundVCFactory");

        ChainDataImpl chainData = null;
        boolean found = false;
        int hashKey = 0;

        // Build a hash key based on names of channel factories.
        for (OutboundChannelDefinition def : channelDefs) {
            hashKey += def.getOutboundFactory().hashCode();
        }

        // See if the key already exists in the current set of outbound chains.
        OutboundVirtualConnectionFactoryImpl vcf = null;
        Iterator<OutboundVirtualConnectionFactoryImpl> vcfs = this.outboundVCFactories.values().iterator();
        while (vcfs.hasNext()) {
            vcf = vcfs.next();
            chainData = (ChainDataImpl) vcf.getChain().getChainData();
            if (hashKey == chainData.getChannelFactoryHash()) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Found matching hash keys");
                }
                // Handle tiny case where two chains hash to same value.
                // Verify the channel factories, factory props, and channel
                // props are the same.
                ChannelData channelDataList[] = chainData.getChannelList();
                if (channelDataList.length == channelDefs.size()) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Found matching number of channels");
                    }
                    // Assume a match.
                    found = true;
                    ChannelData existingDef;
                    ChannelFactoryData existingFactoryData;
                    OutboundChannelDefinition inputDef;
                    // Loop through all the channels in the chain data.
                    for (int i = 0; i < channelDataList.length; i++) {
                        // Extract the current/existing channel def.
                        existingDef = channelDataList[i];
                        existingFactoryData = getChannelFactory(existingDef.getFactoryType());
                        // Extract the new channel def.
                        inputDef = channelDefs.get(i);
                        // Compare the existing and new channel defs.
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Comparing existing def " + existingDef.getFactoryType() + "to new def " + inputDef.getOutboundFactory());
                        }
                        boolean sameFactoryType = (existingDef.getFactoryType() == inputDef.getOutboundFactory());
                        boolean sameChannelProps = propertiesIncluded(inputDef.getOutboundChannelProperties(), existingDef.getPropertyBag());
                        boolean sameFactoryProps = propertiesIncluded(inputDef.getOutboundFactoryProperties(), existingFactoryData.getProperties());

                        if (!sameFactoryType || !sameChannelProps || !sameFactoryProps) {
                            // Found a mismatch.
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(tc, "Keys matched, but factories didn't");
                            }
                            found = false;
                            // Break out of this inner loop.
                            break;
                        }
                    }
                    if (found) {
                        // Break out of outer loop.
                        break;
                    }
                }
            }
        } // factory loop

        if (!found) {
            // Couldn't find a match. Need to create a one.
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "No existing VCF, create one.");
            }
            // We may be able to reuse existing chain or channel data objects.
            // However, the hit in searching probably isn't worth it.
            // For now, create them all from scratch.
            String channelNameList[] = new String[channelDefs.size()];
            String channelName = null;
            int i = 0;
            for (OutboundChannelDefinition def : channelDefs) {
                channelName = "channel_" + channelNameCounter.getAndIncrement();
                channelNameList[i++] = channelName;
                addChannel(channelName, def.getOutboundFactory(), def.getOutboundChannelProperties());
            }
            String chainName = "chain_" + chainNameCounter.getAndIncrement();
            addChain(chainName, FlowType.OUTBOUND, channelNameList);
            vcf = (OutboundVirtualConnectionFactoryImpl) getOutboundVCFactory(chainName);
        } else if (null != vcf) {
            vcf.incrementRefCount();
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Found an existing vcf " + vcf.hashCode());
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "getOutboundVCFactory");
        }
        return vcf;
    }
1121962
private void initSupportExecutor() {
        if (supportExecutor == null || supportExecutor.isShutdown()) {
            supportExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    String maskedRemote = URLUtils.sanitizeURL(remote);
                    return new Thread(r, "CBLPusherSupportExecutor-" + maskedRemote);
                }
            });
        }
    }
582887
public ThreadContext getThreadContext() {
        if (useInheritableThreadLocal && !SSLConfigManager.getInstance().isServerProcess()) {
            ThreadContext context = inheritableThreadLocStorage.get();

            if (context == null) {
                context = new ThreadContext();
                inheritableThreadLocStorage.set(context);
            }
            return context;
        }
        ThreadContext context = threadLocStorage.get();

        if (context == null) {
            context = new ThreadContext();
            threadLocStorage.set(context);
        }

        return context;
    }
76493
@SuppressWarnings("rawtypes")
    public void prepare(Map stormConf) {
        this.stormConf = stormConf;

        int maxWorkers = Utils.getInt(stormConf.get(Config.STORM_MESSAGING_NETTY_CLIENT_WORKER_THREADS));
        ThreadFactory bossFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "boss");
        ThreadFactory workerFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "worker");

        if (maxWorkers > 0) {
            clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
                    Executors.newCachedThreadPool(workerFactory), maxWorkers);
        } else {
            clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
                    Executors.newCachedThreadPool(workerFactory));
        }

        reconnector = new ReconnectRunnable();
        new AsyncLoopThread(reconnector, true, Thread.MIN_PRIORITY, true);
    }
1049108
ThreadPoolExecutor createExecutor(final String threadPrefix, final int workerCount, int queueSize) {
		ThreadFactory threadFactory = new ThreadFactory() {
			private int counter = 0;
			@Override
			public Thread newThread(Runnable runnable) {
				return new Thread(runnable, threadPrefix + "-" + ++counter);
			}
		};
		ThreadPoolExecutor executor = new ThreadPoolExecutor(workerCount, workerCount,
				0, TimeUnit.SECONDS,
				new LinkedBlockingQueue<Runnable>(queueSize), threadFactory);
		return executor;
	}