gpt4 book ai didi

java - 运行 HttpServer 时无法创建新的 native 线程

转载 作者:行者123 更新时间:2023-12-01 12:11:26 27 4
gpt4 key购买 nike

我设置了一个简单的 REST 服务,该服务从另一个服务接收数据并将其放入数据库中。我计划将其作为包含服务和服务器的 jar 文件运行。我的代码是:

public class Main {
public static void main(String[] args) throws IOException {
ResourceConfig config = new DefaultResourceConfig(MyResource.class);
HttpServer server = HttpServerFactory.create("http://localhost:8080/", config);
server.start();
// ...
}

我的资源

@Path("/rest")
public class MyResource {

public MyResource(){
dbConnection = new DbConnection();
}

private final DbConnection dbConnection;

@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_XML)
public Response addItem(MyItem dao){
dbConnection.addItem(dao);
return Response.status(200).build();
}

在 DbConnection 中,构造函数中的 MysqlDataSource ,一旦它获取一个项目,就会将其放入 blockingQueue 中,另一个线程正在监听并处理对数据库的写入。

现在的问题是,每次收到新请求时,都会重新创建 MyResource,调用构造函数,因此再次启动 DbConnection 类及其附带的所有内容。如何避免呢?结果是:

com.sun.jersey.api.container.MappableContainerException: java.lang.OutOfMemoryError: unable to create new native thread
at com.sun.jersey.server.impl.resource.PerRequestFactory$PerRequest._getInstance(PerRequestFactory.java:189)
at com.sun.jersey.server.impl.resource.PerRequestFactory$AbstractPerRequest.getInstance(PerRequestFactory.java:144)
at com.sun.jersey.server.impl.application.WebApplicationContext.getResource(WebApplicationContext.java:239)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:83)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
Caused by: java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:714)
at myPackage.Db.DbConnection.<init>(DbConnection.java:61)
at myPackage.MyResource.<init>(MyResource.java:21)
at sun.reflect.GeneratedConstructorAccessor19.newInstance(Unknown Source)
Exception in thread "Thread-2" java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:714)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:949)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1371)
at sun.net.httpserver.ServerImpl$Dispatcher.handle(ServerImpl.java:433)
at sun.net.httpserver.ServerImpl$Dispatcher.run(ServerImpl.java:398)
at java.lang.Thread.run(Thread.java:745)

最佳答案

将您的资源类注释为@Singleton另请参阅此答案 When to use @Singleton annotation of Jersey?

关于java - 运行 HttpServer 时无法创建新的 native 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27251431/

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