如果存在一个固定大小的对象池(apache commons),并且server.tomcat.threads.max设置为相同的值,那么它是否可以防止池耗尽?如果类是 @Component ,那么这样做是否安全?
Spring代码如下:
简单盒子类:
package com.example.confusion;
public class Box {
}
boxfactory:
package com.example.confusion;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
public class BoxFactory extends BasePooledObjectFactory<Box> {
@Override
public void passivateObject(PooledObject<Box> p) throws Exception {
super.passivateObject(p);
}
@Override
public Box create() throws Exception {
return new Box();
}
@Override
public PooledObject<Box> wrap(Box box) {
return new DefaultPooledObject<Box>(box);
}
}
具有池的类(在控制器中自动连接)
package com.example.confusion;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.stereotype.Component;
@Component
public class BlaBla {
GenericObjectPool<Box> pool;
BoxFactory factory;
public BlaBla() {
GenericObjectPoolConfig poolCnf = new GenericObjectPoolConfig<>();
poolCnf.setMaxTotal(200);
poolCnf.setMaxIdle(200);
poolCnf.setMinIdle(200);
poolCnf.setBlockWhenExhausted(false);
this.factory = new BoxFactory();
this.pool = new GenericObjectPool<Box>(factory, poolCnf);
}
public Box getBox() throws Exception {
return pool.borrowObject();
}
}
控制员:
package com.example.confusion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicInteger;
@RestController
public class BoxController {
@Autowired
BlaBla blabla;
static AtomicInteger count;
static {
count = new AtomicInteger(0);
}
@RequestMapping("/box")
public String getObjectAndWaitForever() {
Box myBox;
try {
synchronized(this) {
myBox = blabla.getBox();
count.incrementAndGet();
System.out.println(count);
}
}
catch(Exception e) {
System.out.println("Box on fire - Objects finished");
}
while(true) {
// I will wait forever
}
}
}
application.properties:
server.tomcat.threads.max=200
将此设置为300会耗尽池中的水,而当设置为200时,它只会在那里等待。
用于测试的shell脚本(启动400个后台进程)
for i in `seq 1 400`; do curl localhost:8080/box & done
暂无答案!
目前还没有任何答案,快来回答吧!