`
Donald_Draper
  • 浏览: 950970 次
社区版块
存档分类
最新评论

Tomcat的StandardService,Executor初始化与启动

阅读更多
Tomcat的Server初始化及启动过程:http://donald-draper.iteye.com/blog/2327060
public class StandardService extends LifecycleMBeanBase implements Service {
    private static final String info =
        "org.apache.catalina.core.StandardService/1.0";
    private String name = null;
    private static final StringManager sm =
        StringManager.getManager(Constants.Package);
    private Server server = null;
    protected Connector connectors[] = new Connector[0];
    private final Object connectorsLock = new Object();
    protected ArrayList<Executor> executors = new ArrayList<Executor>();
    protected Container container = null;
    private ClassLoader parentClassLoader = null;

    // Initialize any Executors
    protected void initInternal() throws LifecycleException {
        for (Executor executor : findExecutors()) {
            if (executor instanceof LifecycleMBeanBase) {
                ((LifecycleMBeanBase) executor).setDomain(getDomain());
            }
            executor.init();
        }
    }
    protected void startInternal() throws LifecycleException {
        synchronized (executors) {
            for (Executor executor: executors) {
	        //启动executor
                executor.start();
            }
        }
    }
}

来看StandardThreadExecutor
public class StandardThreadExecutor extends LifecycleMBeanBase
        implements Executor, ResizableExecutor {
	  // ---------------------------------------------- Properties
    /**
     * Default thread priority
     */
    protected int threadPriority = Thread.NORM_PRIORITY;

    /**
     * Run threads in daemon or non-daemon state
     */
    protected boolean daemon = true;
    
    /**
     * Default name prefix for the thread name
     */
    protected String namePrefix = "tomcat-exec-";
    
    /**
     * max number of threads
     */
    protected int maxThreads = 200;
    
    /**
     * min number of threads
     */
    protected int minSpareThreads = 25;
      /**
     * idle time in milliseconds
     */
    protected int maxIdleTime = 60000;
    
    /**
     * The executor we use for this component
     */
    protected ThreadPoolExecutor executor = null;
    
    /**
     * the name of this thread pool
     */
    protected String name;
     /**
     * The maximum number of elements that can queue up before we reject them
     */
    protected int maxQueueSize = Integer.MAX_VALUE;
    private TaskQueue taskqueue = null;
    //初始化、调用父类的initInternal,注册到Mbean到JVM
      protected void initInternal() throws LifecycleException {
        super.initInternal();
    }
    /**
     * Start the component and implement the requirements
     * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
    //启动
    protected void startInternal() throws LifecycleException {
        //创建任务队列
        taskqueue = new TaskQueue(maxQueueSize);
	//创建任务线程工厂
        TaskThreadFactory tf = new TaskThreadFactory(namePrefix,daemon,getThreadPriority());
	//创建线程执行器
        executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), maxIdleTime, TimeUnit.MILLISECONDS,taskqueue, tf);
        executor.setThreadRenewalDelay(threadRenewalDelay);
        if (prestartminSpareThreads) {
            executor.prestartAllCoreThreads();
        }
        taskqueue.setParent(executor);
        setState(LifecycleState.STARTING);
    }

//查看TaskQueue
/**
 * As task queue specifically designed to run with a thread pool executor.
 * The task queue is optimised to properly utilize threads within
 * a thread pool executor. If you use a normal queue, the executor will spawn threads
 * when there are idle threads and you wont be able to force items unto the queue itself
 *
 */
TaskQueue继承了LinkedBlockingQueue
public class TaskQueue extends LinkedBlockingQueue<Runnable> {
    private ThreadPoolExecutor parent = null;
    // no need to be volatile, the one times when we change and read it occur in
    // a single thread (the one that did stop a context and fired listeners)
    private Integer forcedRemainingCapacity = null;
    @Override
    //如果可能的话,将Runnable加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则返回false。
    public boolean offer(Runnable o) {
      //we can't do any checks
        if (parent==null) return super.offer(o);
        //we are maxed out on threads, simply queue the object
        if (parent.getPoolSize() == parent.getMaximumPoolSize()) return super.offer(o);
        //we have idle threads, just add it to the queue
        if (parent.getSubmittedCount()<(parent.getPoolSize())) return super.offer(o);
        //if we have less threads than maximum force creation of a new thread
        if (parent.getPoolSize()<parent.getMaximumPoolSize()) return false;
        //if we reached here, we need to add it to the queue
        return super.offer(o);
    }
    @Override
    //获取并移除此队列的头Runnable,若不能立即取出,则可以等time参数规定的时间,取不到时返回null。
    public Runnable poll(long timeout, TimeUnit unit)
            throws InterruptedException {
        Runnable runnable = super.poll(timeout, unit);
        if (runnable == null && parent != null) {
            // the poll timed out, it gives an opportunity to stop the current
            // thread if needed to avoid memory leaks.
            parent.stopCurrentThreadIfNeeded();
        }
        return runnable;
    }

    @Override
    //获取BlockingQueue里排在首位的对象Runnable,若BlockingQueue为空,阻断进入等待状态直到BlockingQueue有新的对象被加入为止
    public Runnable take() throws InterruptedException {
        if (parent != null && parent.currentThreadShouldBeStopped()) {
            return poll(parent.getKeepAliveTime(TimeUnit.MILLISECONDS),
                    TimeUnit.MILLISECONDS);
            // yes, this may return null (in case of timeout) which normally
            // does not occur with take()
            // but the ThreadPoolExecutor implementation allows this
        }
        return super.take();
    }
 }

//查看TaskThreadFactory
/**
 * Simple task thread factory to use to create threads for an executor implementation.
 */
public class TaskThreadFactory implements ThreadFactory {
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;
    private final boolean daemon;
    private final int threadPriority;
    public TaskThreadFactory(String namePrefix, boolean daemon, int priority) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        this.namePrefix = namePrefix;
        this.daemon = daemon;
        this.threadPriority = priority;
    }

    @Override
    public Thread newThread(Runnable r) {
        TaskThread t = new TaskThread(group, r, namePrefix + threadNumber.getAndIncrement());
        t.setDaemon(daemon);
        t.setPriority(threadPriority);
        return t;
    }
}

查看ThreadPoolExecutor
ThreadPoolExecutor继承了java.util.concurrent.ThreadPoolExecutor 
public class ThreadPoolExecutor extends java.util.concurrent.ThreadPoolExecutor {}

总结:Service启动,所做的事情,就是创建线程执行器
0
1
分享到:
评论

相关推荐

    tomcat启动的问题--apr

    2010-8-11 18:24:13 org.apache.catalina.core.AprLifecycleListener lifecycleEvent 信息: The Apache Tomcat Native library which allows optimal performance in production environments ...再启动tomcat,一切okay

    myTomcat:WebServer + Tomcat源码分析总结

    来自《深入剖析Tomcat》 ...前导工作: org.apache.catalina.startup.Bootstrap启动startup.sh/...StandardServer的初始化(),start()方法调用所有的服务组件(数组)StandardService的初始化(),start()方法,

    how-tomcat-works

    19.4 初始化ManagerServlet 152 19.5 列出已经部署的web应用 153 19.6 启动web应用 154 19.7 关闭web应用 155 第20章 基于JMX的管理 156 20.1 jmx简介 156 20.2 jmx api 157 20.2.1 MBeanServer 157 20.2.2 Object...

    How Tomcat Works: A Guide to Developing Your Own Java Servlet Container

    19.4 初始化ManagerServlet 152 19.5 列出已经部署的web应用 153 19.6 启动web应用 154 19.7 关闭web应用 155 第20章 基于JMX的管理 156 20.1 jmx简介 156 20.2 jmx api 157 20.2.1 MBeanServer 157 20.2.2 Object...

    struts2驱动包

    信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.6.0_10\bin;C:\Program ...

    struts-2.3.8+spring-3.2.1+mybatis-3.2.2架构

    九月 18, 2013 11:39:02 上午 org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina 九月 18, 2013 11:39:02 上午 org.apache.catalina.core.StandardEngine startInternal ...

    android四大组件

    详细描叙了android四大组件和standardservice ,对android学习有很大的帮助。很有用的android资料

    一条命令解决macmnsvc.exe占用8081端口的问题

    从前有一个SpringBoot程序,我启动了它。很不幸启动失败,报错如下: [2020-04-29 16:30:51.086] [main] [ERROR] [apache.catalina.core.StandardService:182 ] - Failed to start connector [Connector...

    信息: Deploying web application directory lx01

    at org.apache.catalina.core.StandardService.start(StandardService.java:519) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start...

Global site tag (gtag.js) - Google Analytics