写一个程序想验证服务器在hold 1w个链接时内存情况。
1.先说下基本参数
web@haha ~> cat /proc/sys/net/ipv4/tcp_rmem
4096 87380 4161536
web@haha ~> cat /proc/sys/net/ipv4/tcp_wmem
4096 16384 4161536
web@haha ~> cat /proc/sys/net/ipv4/tcp_mem
24180 32241 48360
2.测试环境
简单的阿里云服务器,1核1G。。
3.测试代码,java狗o(╯□╰)o,10000个链接去连本地的9090端口
final Selector selector = Selector.open();
InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 9090);
long start = System.currentTimeMillis();
int connected = 0;
int currentConnectionPerIP = 0;
System.out.println("begin");
while (true) {
if (System.currentTimeMillis() - start > 1000 * 60 * 10) {
break;
}
for (; currentConnectionPerIP < 10000; currentConnectionPerIP++) {
SocketChannel ch = SocketChannel.open();
ch.configureBlocking(false);
Socket s = ch.socket();
s.setReuseAddress(true);
ch.register(selector, SelectionKey.OP_CONNECT);
ch.connect(addr);
}
int select = selector.select(1000 * 10); // 10s
if (select > 0) {
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectedKeys.iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
if (key.isConnectable()) {
SocketChannel ch = (SocketChannel) key.channel();
if (ch.finishConnect()) {
++connected;
if (connected % (connectionPerIP / 10) == 0) {
System.out.println("connected: " + connected);
}
key.interestOps(SelectionKey.OP_READ);
}
}
}
selectedKeys.clear();
}
}
4.测试结果
web@haha ~> cat /proc/net/sockstat
sockets: used 20251
TCP: inuse 20053 orphan 0 tw 10 alloc 20054 mem 3
UDP: inuse 7 mem 2
UDPLITE: inuse 0
RAW: inuse 0
FRAG: inuse 0 memory 0
代码运行前内存
web@haha ~> free -m
total used free shared buffers cached
Mem: 994 825 168 0 9 86
-/+ buffers/cache: 728 265
Swap: 0 0 0
代码运行时内存
web@haha ~> free -m
total used free shared buffers cached
Mem: 994 908 85 0 9 86
-/+ buffers/cache: 812 181
Swap: 0 0 0
5.疑问
为什么内存才变化了80多M啊?这里tcp socket内存大小我没改啊,那就读+写=86+16,按100k来算的话,1w个链接不应该才消耗这么少内存啊?修改
举报
=====================================================
系统保留的是8K, 如果你所有的socket都一直很空闲 也都是发的小包 那么socket的内存占用就是8K
10000*8K 不是正好等于80M么~ 而且也说明你除了创建socket之外 也没做其他需要消耗多内存的逻辑.
http://www.zhihu.com/question/31006886#
转载请注明:爱开源 » socket内存占用疑问?
转载请注明:爱开源 » socket内存占用疑问?