当Java中的集合超出容量限制时,会发生什么? [英] What happens when a collection in Java increases beyond capacity?

查看:246
本文介绍了当Java中的集合超出容量限制时,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务,该服务将对它的所有调用暂存到内存中,因为我们不想丢失数据,并且同时由于任何外部依赖性(例如,例如DB),我们都需要使该服务失败).然后,这些分阶段的调用会定期在后台接听并处理.

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.

所以,问题很简单,这是:当由于资源不足而添加列表失败时,我需要捕获或监视什么异常来通知我?会导致VM本身出现OOM,还是存在集合级限制?

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?

如果没有收集级别限制,您将如何建议我监视服务的使用情况?当前,我们有堆使用率和内存使用率指标.够了吗?另外,将JVM配置为在发生OOM错误时终止运行(这是因为VM管理器随后会重新启动其正在终止运行的所有进程).

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).

推荐答案

要抛出的异常是OutOfMemoryException.一旦您的集合耗尽了所有可用的堆空间,就可以在应用程序的任何部分抛出此异常.

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.

但是,如果您知道有可能将其扔给特定的集合,则最好的方法可能是防止这种情况发生,即限制该集合或使用缓存,以便将未使用的实体逐出并按需重新加载.对于轻量级缓存实施,我建议使用Guava的 CacheBuilder .

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.

更新

由于每个人都建议基于FS的存储,所以这是我的轻量级建议:

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

  • CacheBuilder 到从NoSQL DB加载序列化数据
  • Kryo 序列化程序,将您的对象转换为byte[]
  • MapDB 进行存储(或您喜欢的任何其他嵌入式NoSQL解决方案).
  • 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).

这篇关于当Java中的集合超出容量限制时,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆