java如何控制集合的容量,当Java中的集合超出容量限制时会发生什么?

I have a service which stages all calls made to it in memory, because we don't want to lose the data and at the same time we need this service to ever fail due to any external dependency (like a DB for example). These staged calls are then routinely picked up and processed in the background.

If, for any reason, if there are too many calls and we run out of memory, we need to be alarmed.

So, the question simply put, is this: What exception do I need to catch or monitor on to notify me when an addition to a list fails due to insufficient resources? Will it result in an OOM in the VM itself, or is there a collection-level limit as well?

If there is no collection-level limit, how would you recommend I monitor the usage of the service? Currently, we have heap usage and memory usage metrics. Are those enough? Also, the JVMs are configured to kill on an OOM error (this is because the VM manager then restarts any process it is managing on a kill).

解决方案

The exception to be thrown is OutOfMemoryException. This exception can be thrown in any part of your application, once your collection eats all available heap space.

However if you know that it can be potentially thrown for a specific collection, the best way might be to prevent this to happen, i.e. cap this collection or use caching, so that unused entities are evicted and reloaded on demand. For a lightweight cache implementation I would recommend Guava's CacheBuilder.

UPDATE

Since everybody suggests FS-based storage, here is my lightweight drop-in proposal:

CacheBuilder to load your serialized data from NoSQL DB

Kryo serializer to convert your objects into byte[]

MapDB to store (or any other embedded NoSQL solution you prefer).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值