Java Code Examples for org.eclipse.jetty.util.ProcessorUtils

Following code examples demonstrate how to use org.eclipse.jetty.util.ProcessorUtils from jetty. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use org.eclipse.jetty.util.ProcessorUtils and various code implementation of this class.

	public void afterPropertiesSet() throws Exception {
		String name = this.threadPrefix + "@" + Integer.toHexString(hashCode());
		if (this.executor == null) {
			QueuedThreadPool threadPool = new QueuedThreadPool();
			threadPool.setName(name);
			this.executor = threadPool;
		}
		if (this.byteBufferPool == null) {
			this.byteBufferPool = new MappedByteBufferPool(2048,
					this.executor instanceof ThreadPool.SizedThreadPool
							? ((ThreadPool.SizedThreadPool) executor).getMaxThreads() / 2
							: ProcessorUtils.availableProcessors() * 2);
		}
		if (this.scheduler == null) {
			this.scheduler = new ScheduledExecutorScheduler(name + "-scheduler", false);
		}

		if (this.executor instanceof LifeCycle) {
			((LifeCycle)this.executor).start();
		}
		this.scheduler.start();
	} 


    @BeforeClass
    public static void saveState()
    {
        originalCoreCount = ProcessorUtils.availableProcessors();
    } 

    @AfterClass
    public static void restoreState()
    {
        ProcessorUtils.setAvailableProcessors(originalCoreCount);
    } 

    {
        if (executor instanceof ThreadPool.SizedThreadPool)
        {
            int threads = ((ThreadPool.SizedThreadPool)executor).getMaxThreads();
            int cpus = ProcessorUtils.availableProcessors();
            return Math.max(1,Math.min(cpus/2,threads/16));
        }
        return Math.max(1,ProcessorUtils.availableProcessors()/2);
    } 

    
    public ThreadPoolBudget(ThreadPool.SizedThreadPool pool)
    {
        this(pool,Math.min(ProcessorUtils.availableProcessors(),pool.getMinThreads()));
    } 

    protected Connector newServerConnector( Server server) throws Exception {
        if (transport == UNIX_SOCKET)
        {
            UnixSocketConnector
                unixSocketConnector = new UnixSocketConnector( server, provideServerConnectionFactory( transport ));
            unixSocketConnector.setUnixSocket( sockFile.toString() );
            return unixSocketConnector;
        }
        int cores = ProcessorUtils.availableProcessors();
        ByteBufferPool byteBufferPool = new ArrayByteBufferPool();
        byteBufferPool = new LeakTrackingByteBufferPool(byteBufferPool);
        return new ServerConnector(server, null, null, byteBufferPool,
                1, Math.min(1, cores / 2), provideServerConnectionFactory(transport));
    } 

    public void start() {
        try {
            LOG.info("At startup: JVM {} processors, and Jetty {} processors", Runtime.getRuntime().availableProcessors(), ProcessorUtils.availableProcessors());
            readManifests();
        } catch (IOException e) {
            LOG.debug("Error while reading manifest", e);
        }
    } 

    
    private static int reservedThreads(Executor executor,int capacity)
    {
        if (capacity>=0)
            return capacity;
        int cpus = ProcessorUtils.availableProcessors();
        if (executor instanceof ThreadPool.SizedThreadPool)
        {
            int threads = ((ThreadPool.SizedThreadPool)executor).getMaxThreads();
            return Math.max(1, Math.min(cpus, threads / 10));
        }
        return cpus;
    } 

    }

    public ExecutorThreadPool(ThreadPoolExecutor executor, int reservedThreads, ThreadGroup group)
    {
        this( executor, Math.min(ProcessorUtils.availableProcessors(),executor.getCorePoolSize()),reservedThreads,group);
    } 

    @Override
    protected HttpClient newHttpClient()
    {
        ServletConfig config = getServletConfig();
        String scriptRoot = config.getInitParameter(SCRIPT_ROOT_INIT_PARAM);
        if (scriptRoot == null)
            throw new IllegalArgumentException("Mandatory parameter '" + SCRIPT_ROOT_INIT_PARAM + "' not configured");
        int selectors = Math.max( 1, ProcessorUtils.availableProcessors() / 2);
        String value = config.getInitParameter("selectors");
        if (value != null)
            selectors = Integer.parseInt(value);
        return new HttpClient(new ProxyHttpClientTransportOverFCGI(selectors, scriptRoot), null);
    } 

    @Override
    public void init() throws ServletException
    {
        String tmp = getInitParameter("buffersize");
        if (tmp!=null)
            buffersize=Integer.parseInt(tmp);
        tmp = getInitParameter("pause");
        if (tmp!=null)
            pauseNS=TimeUnit.MILLISECONDS.toNanos(Integer.parseInt(tmp));
        tmp = getInitParameter("pool");
        int pool=tmp==null?ProcessorUtils.availableProcessors():Integer.parseInt(tmp);
        
        scheduler=new ScheduledThreadPoolExecutor(pool);
    } 

    
    public AbstractConnector(
            Server server,
            Executor executor,
            Scheduler scheduler,
            ByteBufferPool pool,
            int acceptors,
            ConnectionFactory... factories)
    {
        _server=server;
        _executor=executor!=null?executor:_server.getThreadPool();
        if (scheduler==null)
            scheduler=_server.getBean(Scheduler.class);
        _scheduler=scheduler!=null?scheduler:new ScheduledExecutorScheduler();
        if (pool==null)
            pool=_server.getBean(ByteBufferPool.class);
        _byteBufferPool = pool!=null?pool:new ArrayByteBufferPool();

        addBean(_server,false);
        addBean(_executor);
        if (executor==null)
        addBean(_scheduler);
        addBean(_byteBufferPool);

        for (ConnectionFactory factory:factories)
            addConnectionFactory(factory);

        int cores = ProcessorUtils.availableProcessors();
        if (acceptors < 0)
            acceptors=Math.max(1, Math.min(4,cores/8));
        if (acceptors > cores)
            LOG.warn("Acceptors should be <= availableProcessors: " + this);
        _acceptors = new Thread[acceptors];
    } 

    @Override
    protected void doStart() throws Exception
    {
        if (executor == null)
        {
            QueuedThreadPool threadPool = new QueuedThreadPool();
            threadPool.setName(name);
            setExecutor(threadPool);
        }

        if (byteBufferPool == null)
            setByteBufferPool(new MappedByteBufferPool(2048,
                    executor instanceof ThreadPool.SizedThreadPool
                            ? ((ThreadPool.SizedThreadPool)executor).getMaxThreads() / 2
                            : ProcessorUtils.availableProcessors() * 2));

        if (scheduler == null)
            setScheduler(new ScheduledExecutorScheduler(name + "-scheduler", false));

        if (resolver == null)
            setSocketAddressResolver(new SocketAddressResolver.Async(executor, scheduler, getAddressResolutionTimeout()));

        handlers.put(new ContinueProtocolHandler());
        handlers.put(new RedirectProtocolHandler(this));
        handlers.put(new WWWAuthenticationProtocolHandler(this));
        handlers.put(new ProxyAuthenticationProtocolHandler(this));

        decoderFactories.add(new GZIPContentDecoder.Factory(byteBufferPool));

        cookieManager = newCookieManager();
        cookieStore = cookieManager.getCookieStore();

        transport.setHttpClient(this);
        super.doStart();
    } 

    
    protected HttpClient newHttpClient()
    {
        int selectors = Math.max(1,ProcessorUtils.availableProcessors()/2);
        String value = getServletConfig().getInitParameter("selectors");
        if (value != null)
            selectors = Integer.parseInt(value);
        return new HttpClient(new HttpClientTransportOverHTTP(selectors),null);
    } 

    
    protected void scanForAnnotations (WebAppContext context)
    throws Exception
    {
        int javaPlatform = 0;
        Object target = context.getAttribute(JavaVersion.JAVA_TARGET_PLATFORM);
        if (target!=null)
            javaPlatform = Integer.valueOf(target.toString());
        AnnotationParser parser = createAnnotationParser(javaPlatform);
        _parserTasks = new ArrayList<ParserTask>();

        long start = 0; 


        if (LOG.isDebugEnabled())
            LOG.debug("Annotation scanning commencing: webxml={}, metadatacomplete={}, configurationDiscovered={}, multiThreaded={}, maxScanWait={}", 
                      context.getServletContext().getEffectiveMajorVersion(), 
                      context.getMetaData().isMetaDataComplete(),
                      context.isConfigurationDiscovered(),
                      isUseMultiThreading(context),
                      getMaxScanWait(context));

             
        parseContainerPath(context, parser);
        parseWebInfClasses(context, parser);
        parseWebInfLib (context, parser); 
        
        start = System.nanoTime();
        
        final Semaphore task_limit = (isUseMultiThreading(context)? new Semaphore(ProcessorUtils.availableProcessors()):new Semaphore( 1));
        final CountDownLatch latch = new CountDownLatch(_parserTasks.size());
        final MultiException me = new MultiException();
    
        for (final ParserTask p:_parserTasks)
        {
            task_limit.acquire();
            context.getServer().getThreadPool().execute(new Runnable()
            {
                @Override
                public void run()
                {
                   try
                   {
                       p.call();
                   }
                   catch (Exception e)
                   {
                       me.add(e);
                   }
                   finally
                   {
                       task_limit.release();
                       latch.countDown();
                   }
                }         
            });
        }
       
        boolean timeout = !latch.await(getMaxScanWait(context), TimeUnit.SECONDS);
        long elapsedMs = TimeUnit.MILLISECONDS.convert(System.nanoTime()-start, TimeUnit.NANOSECONDS);
        
        LOG.info("Scanning elapsed time={}ms",elapsedMs);
          
        if (LOG.isDebugEnabled())
        {
            for (ParserTask p:_parserTasks)
                LOG.debug("Scanned {} in {}ms", p.getResource(), TimeUnit.MILLISECONDS.convert(p.getStatistic().getElapsed(), TimeUnit.NANOSECONDS));

            LOG.debug("Scanned {} container path jars, {} WEB-INF/lib jars, {} WEB-INF/classes dirs in {}ms for context {}",
                    (_containerPathStats==null?-1:_containerPathStats.getTotal()), 
                    (_webInfLibStats==null?-1:_webInfLibStats.getTotal()), 
                    (_webInfClassesStats==null?-1:_webInfClassesStats.getTotal()),
                    elapsedMs,
                    context);
        }

        if (timeout)
            me.add(new Exception("Timeout scanning annotations"));
        me.ifExceptionThrow();   
    } 

Advertisement
Javadoc


ProcessorUtils provides access to runtime info about processors, that may be overridden by

system properties or environment variables.

This can be useful in virtualized environments where the runtime may miss report the available resources.

Read More
Advertisement