首页 > 解决方案 > java.lang.OutOfMemoryError:无法创建新的本地线程

问题描述

在大约 1024 个线程之后,我们在 jboss 上收到“java.lang.OutOfMemoryError:无法创建新的本机线程”,因为应用程序消耗了所有最大用户进程

ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 14866
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
**max user processes              (-u) 1024**
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

这一切发生的代码如下:

ExecutorService service = Executors.newFixedThreadPool(2);  
Collection<Callable<String>> tasks = new ArrayList<Callable<String>>();  
tasks.add(ctgService); **--> THIS IS THE LINE OF OOM**
try{
    List<Future<String>> taskFutures = service.invokeAll(tasks, 60L, TimeUnit.SECONDS);  
    for (Future<String> future : taskFutures) {  
        ctgMsgOut = future.get();
    }  
} catch (InterruptedException ie){
     throw new TimeoutException("The response from GEC-CTG has exceeded the timeout");
} catch (CancellationException ce){
    throw new TimeoutException("The response from GEC-CTG has exceeded the timeout");           
} catch (ExecutionException ee){
    if (ee.getCause() instanceof TimeoutException){
        throw new TimeoutException("The response from GEC-CTG has exceeded the timeout");
    }else{
        throw new ConnectException("Connect exception");
    }
} catch (Exception e){  
        e.printStackTrace();
}finally {
    service.shutdown();
}
ctgMsgOut = "<MessageOutGEC>" + ctgMsgOut +  "</MessageOutGEC>";
            
exchange.getOut().setBody(ctgMsgOut, String.class);

exchange.getOut().setHeaders(exchange.getIn().getHeaders());

请你能帮我理解代码不正确的地方吗?在 service.shutdown() 之后我应该添加 tasks.clear() 还是 tasks.remove(ctgService)?

谢谢

标签: javajbossout-of-memory

解决方案


如果在一个rest方法中调用这段代码,rest方法被并行调用600次,会同时创建1200个线程。

让所有方法调用都使用相同的ExecutorService service = Executors.newFixedThreadPool(2);- 或者ManagedExecutorService如果您在现代 jboss/wildfly 中,最好注入 a 。


推荐阅读