Example usage for java.lang ThreadGroup ThreadGroup

List of usage examples for java.lang ThreadGroup ThreadGroup

Introduction

In this page you can find the example usage for java.lang ThreadGroup ThreadGroup.

Prototype

public ThreadGroup(String name) 

Source Link

Document

Constructs a new thread group.

Usage

From source file:org.apache.wicket.threadtest.tester.Tester.java

/**
 * Runs the test./*from www .  j  a v a2  s . co m*/
 * 
 * @throws Exception
 */
public void run() throws Exception {

    activeThreads = 0;

    HttpConnectionManagerParams connManagerParams = new HttpConnectionManagerParams();
    connManagerParams.setDefaultMaxConnectionsPerHost(numberOfThreads * 2);
    MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
    manager.setParams(connManagerParams);

    Server server = null;
    GetMethod getMethod = new GetMethod("http://localhost:" + port + "/");
    try {
        getMethod.setFollowRedirects(true);
        HttpClient httpClient = new HttpClient(params, manager);
        int code = httpClient.executeMethod(getMethod);
        if (code != 200) {
            server = startServer(port);
        }
    } catch (Exception e) {
        server = startServer(port);
    } finally {
        getMethod.releaseConnection();
    }

    try {

        ThreadGroup g = new ThreadGroup("runners");
        Thread[] threads = new Thread[numberOfThreads];
        HttpClient client = null;
        for (int i = 0; i < numberOfThreads; i++) {

            if (multipleSessions) {
                client = new HttpClient(params, manager);
                client.getHostConfiguration().setHost(host, port);
            } else {
                if (client == null) {
                    client = new HttpClient(params, manager);
                    client.getHostConfiguration().setHost(host, port);
                }
            }
            threads[i] = new Thread(g, new CommandRunner(commands, client, this));
        }

        long start = System.currentTimeMillis();

        for (int i = 0; i < numberOfThreads; i++) {
            activeThreads++;
            threads[i].start();
        }

        while (activeThreads > 0) {
            synchronized (this) {
                wait();
            }
        }

        long end = System.currentTimeMillis();
        long time = end - start;
        log.info("\n******** finished in " + Duration.milliseconds(time) + " (" + time + " milis)");

    } finally {
        MultiThreadedHttpConnectionManager.shutdownAll();
        if (server != null) {
            server.stop();
        }
    }
}

From source file:com.espertech.esper.core.thread.ThreadingServiceImpl.java

private ThreadPoolExecutor getThreadPool(String engineURI, String name, BlockingQueue<Runnable> queue,
        int numThreads) {
    if (log.isInfoEnabled()) {
        log.info("Starting pool " + name + " with " + numThreads + " threads");
    }/*from w w  w. j  a  v  a2 s .  c o  m*/

    if (engineURI == null) {
        engineURI = "default";
    }

    String threadGroupName = "com.espertech.esper." + engineURI + "-" + name;
    ThreadGroup threadGroup = new ThreadGroup(threadGroupName);
    ThreadPoolExecutor pool = new ThreadPoolExecutor(numThreads, numThreads, 1, TimeUnit.SECONDS, queue,
            new EngineThreadFactory(engineURI, name, threadGroup, Thread.NORM_PRIORITY));
    pool.prestartAllCoreThreads();

    return pool;
}

From source file:com.espertech.esper.core.thread.ThreadingServiceImpl.java

public Thread makeEventSourceThread(String engineURI, String sourceName, Runnable runnable) {
    if (engineURI == null) {
        engineURI = "default";
    }//from  www  .  ja  v  a2s.  co m

    String threadGroupName = "com.espertech.esper." + engineURI + "-source-" + sourceName;
    ThreadGroup threadGroup = new ThreadGroup(threadGroupName);
    return new Thread(threadGroup, runnable);
}

From source file:org.apache.synapse.transport.passthru.PassThroughHttpSender.java

public void init(ConfigurationContext configurationContext, TransportOutDescription transportOutDescription)
        throws AxisFault {
    log.info("Initializing Pass-through HTTP/S Sender...");

    namePrefix = transportOutDescription.getName().toUpperCase(Locale.US);
    scheme = getScheme();//ww w. ja v a2s . c  om

    WorkerPool workerPool = null;
    Object obj = configurationContext.getProperty(PassThroughConstants.PASS_THROUGH_TRANSPORT_WORKER_POOL);
    if (obj != null) {
        workerPool = (WorkerPool) obj;
    }

    PassThroughTransportMetricsCollector metrics = new PassThroughTransportMetricsCollector(false,
            scheme.getName());
    TransportView view = new TransportView(null, this, metrics, null);
    MBeanRegistrar.getInstance().registerMBean(view, "Transport",
            "passthru-" + namePrefix.toLowerCase() + "-sender");

    proxyConfig = new ProxyConfigBuilder().parse(transportOutDescription).build();
    if (log.isInfoEnabled() && proxyConfig.getProxy() != null) {
        log.info("HTTP Sender using Proxy " + proxyConfig.getProxy() + " bypassing "
                + proxyConfig.getProxyBypass());
    }

    targetConfiguration = new TargetConfiguration(configurationContext, transportOutDescription, workerPool,
            metrics, proxyConfig.getCreds() != null ? new ProxyAuthenticator(proxyConfig.getCreds()) : null);
    targetConfiguration.build();

    PassThroughSenderManager.registerPassThroughHttpSender(this);

    configurationContext.setProperty(PassThroughConstants.PASS_THROUGH_TRANSPORT_WORKER_POOL,
            targetConfiguration.getWorkerPool());

    ClientConnFactoryBuilder connFactoryBuilder = initConnFactoryBuilder(transportOutDescription);
    connFactory = connFactoryBuilder.createConnFactory(targetConfiguration.getHttpParams());

    try {
        String prefix = namePrefix + "-Sender I/O dispatcher";

        ioReactor = new DefaultConnectingIOReactor(targetConfiguration.getIOReactorConfig(),
                new NativeThreadFactory(new ThreadGroup(prefix + " Thread Group"), prefix));

        ioReactor.setExceptionHandler(new IOReactorExceptionHandler() {

            public boolean handle(IOException ioException) {
                log.warn("System may be unstable: " + namePrefix
                        + " ConnectingIOReactor encountered a checked exception : " + ioException.getMessage(),
                        ioException);
                return true;
            }

            public boolean handle(RuntimeException runtimeException) {
                log.warn("System may be unstable: " + namePrefix
                        + " ConnectingIOReactor encountered a runtime exception : "
                        + runtimeException.getMessage(), runtimeException);
                return true;
            }
        });
    } catch (IOReactorException e) {
        handleException("Error starting " + namePrefix + " ConnectingIOReactor", e);
    }

    ConnectCallback connectCallback = new ConnectCallback();

    targetConnections = new TargetConnections(ioReactor, targetConfiguration, connectCallback);
    targetConfiguration.setConnections(targetConnections);

    // create the delivery agent to hand over messages
    deliveryAgent = new DeliveryAgent(targetConfiguration, targetConnections, proxyConfig);
    // we need to set the delivery agent
    connectCallback.setDeliveryAgent(deliveryAgent);

    handler = new TargetHandler(deliveryAgent, connFactory, targetConfiguration);
    ioEventDispatch = new ClientIODispatch(handler, connFactory);

    // start the sender in a separate thread
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (Exception ex) {
                log.fatal("Exception encountered in the " + namePrefix + " Sender. "
                        + "No more connections will be initiated by this transport", ex);
            }
            log.info(namePrefix + " Sender shutdown");
        }
    }, "PassThrough" + namePrefix + "Sender");
    t.start();

    state = BaseConstants.STARTED;

    log.info("Pass-through " + namePrefix + " Sender started...");
}

From source file:org.apache.axis2.transport.xmpp.XMPPListener.java

/**
 * Start a pool of Workers. For each connection in connectionFactories,
 * assign a packer listener. This packet listener will trigger when a 
 * message arrives.//from www . ja v  a2s .  c  o  m
 */
public void start() throws AxisFault {
    // create thread pool of workers
    ExecutorService workerPool = new ThreadPoolExecutor(1, WORKERS_MAX_THREADS, WORKER_KEEP_ALIVE, TIME_UNIT,
            new LinkedBlockingQueue(), new org.apache.axis2.util.threadpool.DefaultThreadFactory(
                    new ThreadGroup("XMPP Worker thread group"), "XMPPWorker"));

    Iterator iter = connectionFactories.values().iterator();
    while (iter.hasNext()) {
        XMPPConnectionFactory connectionFactory = (XMPPConnectionFactory) iter.next();
        XMPPPacketListener xmppPacketListener = new XMPPPacketListener(connectionFactory,
                this.configurationContext, workerPool);
        connectionFactory.listen(xmppPacketListener);
    }
}

From source file:org.nuxeo.ecm.core.repository.jcr.lock.RepositorySessionLockStress.java

protected void startRunners() throws InterruptedException {
    canDispose = new CountDownLatch(numberOfThreads);
    canStart = new CountDownLatch(1);
    ThreadGroup group = new ThreadGroup(RepositorySessionLockStress.class.getSimpleName());
    OperationRunner[] runners = new OperationRunner[numberOfThreads];
    for (int i = 0; i < numberOfThreads; i++) {
        OperationRunner runner;//from  w  w  w. ja  va  2 s . c  om
        runners[i] = runner = new OperationRunner(formatName(PREFIX, i, numberOfThreads));
        new Thread(group, runner, runner.name).start();
    }
    canStart.countDown();
    canDispose.await();
    for (int i = 0; i < numberOfThreads; i++) {
        OperationRunner runner = runners[i];
        log.info(runner.formatMessage());
        for (Exception error : runner.errors) {
            log.error(runner.name, error);
        }
    }
}

From source file:no.eris.applet.AppletViewer.java

/**
 * Runs the applet. Creates a Frame and adds it to it.
 * @param async whether to start a separate thread running the viewer.
 * @return the started thread or <code>null</code> when async is false
 *///from   www.j ava  2s  .c om
public Thread run(final boolean async) {

    overrideCookieHandler(manager);

    frame = new JFrame("AppletViewer");
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            LOGGER.debug("windowClosing");
            disposeResources();
        }
    });

    Container cp = frame.getContentPane();
    cp.setLayout(new BorderLayout());

    // Instantiate the AppletAdapter which gives us
    // AppletStub and AppletContext.
    if (appletAdapter == null)
        appletAdapter = new AppletAdapter(this, attributes, params);

    // The AppletAdapter also gives us showStatus.
    // Therefore, must add() it very early on, since the Applet's
    // Constructor or its init() may use showStatus()
    cp.add(BorderLayout.SOUTH, appletAdapter);

    showStatus("Loading Applet ");
    if (loadFromLocalClasspath) {
        loadAppletLocaly();
    } else {
        loadAppletRemotely();
    }
    setAppletSize();

    if (applet == null) {
        LOGGER.debug("applet null");
        return null;
    }

    // Now right away, tell the Applet how to find showStatus et al.
    applet.setStub(appletAdapter);

    // Connect the Applet to the Frame.
    cp.add(BorderLayout.CENTER, applet);

    threadGroup = new ThreadGroup("AppletViewer-" + applet.getParameter("name") + "-FIXME_ID");
    threadGroup.setDaemon(true);

    // Here we pretend to be a browser!
    final Runnable task = new Runnable() {
        public void run() {
            applet.init();
            final Dimension d = applet.getSize();
            d.height += appletAdapter.getSize().height;
            frame.setSize(d);
            frame.setVisible(true); // make the Frame and all in it appear
            applet.start();
            showStatus("Applet " + applet.getParameter("name") + " loaded");
            if (async) {
                waitForAppletToClose();
            }
        }
    };
    if (async) {
        Thread t = new Thread(threadGroup, task);
        final ClassLoader loader = applet.getClass().getClassLoader();
        t.setContextClassLoader(loader);
        t.start();
        return t;
    } else {
        task.run();
        return null;
    }
}

From source file:org.apache.synapse.transport.passthru.PassThroughHttpListener.java

public void init(ConfigurationContext cfgCtx, TransportInDescription transportInDescription) throws AxisFault {

    log.info("Initializing Pass-through HTTP/S Listener...");
    pttInDescription = transportInDescription;
    namePrefix = transportInDescription.getName().toUpperCase(Locale.US);
    scheme = initScheme();/*from w w  w.j a  v a2  s . c o  m*/

    int portOffset = Integer.parseInt(System.getProperty("portOffset", "0"));
    Parameter portParam = transportInDescription.getParameter("port");
    int port = Integer.parseInt(portParam.getValue().toString());
    operatingPort = port + portOffset;
    portParam.setValue(String.valueOf(operatingPort));
    portParam.getParameterElement().setText(String.valueOf(operatingPort));

    System.setProperty(transportInDescription.getName() + ".nio.port", String.valueOf(operatingPort));

    Object obj = cfgCtx.getProperty(PassThroughConstants.PASS_THROUGH_TRANSPORT_WORKER_POOL);
    WorkerPool workerPool = null;
    if (obj != null) {
        workerPool = (WorkerPool) obj;
    }

    PassThroughTransportMetricsCollector metrics = new PassThroughTransportMetricsCollector(true,
            scheme.getName());

    TransportView view = new TransportView(this, null, metrics, null);
    MBeanRegistrar.getInstance().registerMBean(view, "Transport",
            "passthru-" + namePrefix.toLowerCase() + "-receiver");

    sourceConfiguration = new SourceConfiguration(cfgCtx, transportInDescription, scheme, workerPool, metrics);
    sourceConfiguration.build();

    HttpHost host = new HttpHost(sourceConfiguration.getHostname(), sourceConfiguration.getPort(),
            sourceConfiguration.getScheme().getName());
    ServerConnFactoryBuilder connFactoryBuilder = initConnFactoryBuilder(transportInDescription, host);
    connFactory = connFactoryBuilder.build(sourceConfiguration.getHttpParams());

    handler = new SourceHandler(sourceConfiguration);
    passThroughListeningIOReactorManager = PassThroughListeningIOReactorManager.getInstance();

    // register to receive updates on services for lifetime management
    //cfgCtx.getAxisConfiguration().addObservers(axisObserver);
    String prefix = namePrefix + "-Listener I/O dispatcher";
    try {
        ioReactor = (DefaultListeningIOReactor) passThroughListeningIOReactorManager.initIOReactor(
                operatingPort, handler,
                new PassThroughSharedListenerConfiguration(
                        new NativeThreadFactory(new ThreadGroup(prefix + " thread group"), prefix), connFactory,
                        sourceConfiguration));
    } catch (IOReactorException e) {
        handleException("Error initiating " + namePrefix + " ListeningIOReactor", e);
    }

    Map<String, String> o = (Map<String, String>) cfgCtx
            .getProperty(PassThroughConstants.EPR_TO_SERVICE_NAME_MAP);
    if (o != null) {
        this.eprToServiceNameMap = o;
    } else {
        eprToServiceNameMap = new HashMap<String, String>();
        cfgCtx.setProperty(PassThroughConstants.EPR_TO_SERVICE_NAME_MAP, eprToServiceNameMap);
    }

    cfgCtx.setProperty(PassThroughConstants.PASS_THROUGH_TRANSPORT_WORKER_POOL,
            sourceConfiguration.getWorkerPool());

    /* register to receive updates on services */
    serviceTracker = new AxisServiceTracker(cfgCtx.getAxisConfiguration(), new AxisServiceFilter() {
        public boolean matches(AxisService service) {
            return !service.getName().startsWith("__") // these are "private" services
                    && BaseUtils.isUsingTransport(service, pttInDescription.getName());
        }
    }, new AxisServiceTrackerListener() {
        public void serviceAdded(AxisService service) {
            addToServiceURIMap(service);
        }

        public void serviceRemoved(AxisService service) {
            removeServiceFfromURIMap(service);
        }
    });

}

From source file:org.apache.axis2.transport.http.server.HttpFactory.java

/**
 * Create the executor used to launch the single requestConnectionListener
 *///  w  w  w  . j  a v  a2s  .  c o m
public ExecutorService newListenerExecutor(int port) {
    return new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(),
            new DefaultThreadFactory(new ThreadGroup("Listener thread group"), "HttpListener-" + this.port));
}