gpt4 book ai didi

java - 非公共(public)构造函数导致 Tomcat7 出现问题?

转载 作者:行者123 更新时间:2023-11-28 22:34:19 26 4
gpt4 key购买 nike

我有一个在 tomcat 上运行 Spring 的 Java 应用程序。

这个类给我带来了一个非常奇怪的问题:

@WebListener
public class ThreadPool extends ThreadPoolExecutor implements ServletContextListener {

private ThreadPool() {
super(MIN_ACTIVE_THREADS, MAX_ACTIVE_THREADS, DEACTIVATE_THREADS_AFTER_TIMEPERIOD, TimeUnit.SECONDS, taskQueue);
}

private static final ThreadPoolExecutor pool = new ThreadPool();

public synchronized static void submit(Task task) {
executingTasks.add(task);
pool.execute(task);
}

@Override
public synchronized void contextDestroyed(ServletContextEvent arg0) {
cancelWaitingTasks();
sendStopSignalsToExecutingTasks();
pool.shutdown();
}

...

}

如果构造函数是私有(private)的或默认的,我会在运行时遇到此异常(在对应用程序的第一个 HTTP 请求时):

Error configuring application listener of class com.testApp.util.ThreadPool
java.lang.IllegalAccessException: Class org.apache.catalina.core.DefaultInstanceManager can not access a member of class com.testApp.util.ThreadPool with modifiers "private"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
at java.lang.Class.newInstance(Class.java:436)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:140)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4888)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Skipped installing application listeners due to previous error(s)
Error listenerStart
Context [] startup failed due to previous errors

但是,如果我将构造函数设置为 public,那么我将不会出现异常,并且一切正常。谁能告诉我为什么这个默认或私有(private)构造函数会导致运行时异常?

最佳答案

Tomcat 使用 Class.newInstance()创建一个 ThreadPool 的实例.此方法遵循 Java 的访问规则。

因为你的构造函数是私有(private)的,所以它失败了 IllegalAccessException .这是运行时等效于不允许调用编译器错误的函数,如果您尝试编写 new ThreadPool() 就会看到该错误在ThreadPool之外,

关于java - 非公共(public)构造函数导致 Tomcat7 出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33960018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com