Hazelcast: что произойдет, если у вас закончится память


Мы планируем использовать Hazelcast для организации очередей Apache Camel messages plus в качестве вторичного кэша гибернации.

Предполагая, что мы настроим нашу очередь на использование целого числа.MAX_VALUE (который, вероятно, не поместится в память) без резервной карты: что произойдет, если используется вся память? Я действительно не могу найти ничего, относящегося к этому сценарию в документации.

<hazelcast>
...
<queue name="tasks">
    <!--
        Maximum size of the queue. When a JVM's local queue size reaches the maximum,
        all put/offer operations will get blocked until the queue size
        of the JVM goes down below the maximum.
        Any integer between 0 and Integer.MAX_VALUE. 0 means Integer.MAX_VALUE. Default is 0.
    -->
    <max-size-per-jvm>0</max-size-per-jvm>

    <!--
        Name of the map configuration that will be used for the backing distributed
        map for this queue.
    -->
    <backing-map-ref></backing-map-ref>
</queue>

То же самое с картами: что произойдет, если нет TTL и политика выселения установлена в Нет, значит, вся карта рано или поздно не поместится в памяти?

<hazelcast>
...
<map name="default">
    <!--
        Number of backups. If 1 is set as the backup-count for example,
        then all entries of the map will be copied to another JVM for
        fail-safety. Valid numbers are 0 (no backup), 1, 2, 3.
    -->
    <backup-count>1</backup-count>

    <!--
        Maximum number of seconds for each entry to stay in the map. Entries that are
        older than <time-to-live-seconds> and not updated for <time-to-live-seconds>
        will get automatically evicted from the map.
        Any integer between 0 and Integer.MAX_VALUE. 0 means infinite. Default is 0.
    -->
    <time-to-live-seconds>0</time-to-live-seconds>

    <!--
        Maximum number of seconds for each entry to stay idle in the map. Entries that are
        idle(not touched) for more than <max-idle-seconds> will get
        automatically evicted from the map.
        Entry is touched if get, put or containsKey is called.
        Any integer between 0 and Integer.MAX_VALUE.
        0 means infinite. Default is 0.
    -->
    <max-idle-seconds>0</max-idle-seconds>

    <!--
        Valid values are:
        NONE (no extra eviction, <time-to-live-seconds> may still apply),
        LRU  (Least Recently Used),
        LFU  (Least Frequently Used).
        NONE is the default.
        Regardless of the eviction policy used, <time-to-live-seconds> will still apply. 
    -->
    <eviction-policy>NONE</eviction-policy>

    <!--
        Maximum size of the map. When max size is reached,
        map is evicted based on the policy defined.
        Any integer between 0 and Integer.MAX_VALUE. 0 means
        Integer.MAX_VALUE. Default is 0.
    -->
    <max-size policy="cluster_wide_map_size">0</max-size>

    <!--
        When max. size is reached, specified percentage of
        the map will be evicted. Any integer between 0 and 100.
        If 25 is set for example, 25% of the entries will
        get evicted.
    -->
    <eviction-percentage>25</eviction-percentage>
   <!--
        Specifies when eviction will be started. Default value is 3. 
       So every 3 (+up to 5 for performance reasons) seconds 
       eviction will be kicked of. Eviction is costly operation, setting 
       this number too low, can decrease the performance. 
   -->
  <eviction-delay-seconds>3</eviction-delay-seconds>
</map>
</hazelcast>

Хотя это довольно глупая конфигурация, это всего лишь пример для ситуации, когда у вас заканчивается память.

2 3

2 ответа:

В случае очереди, если вы не можете потреблять так же быстро, как производите, то в конечном итоге вы можете выйти из памяти, то есть JVM будет выбрасывать исключение OutOfMemoryException при попытке создать новые объекты. Обычно рекомендуется иметь максимальный размер очереди,если есть все возможности иметь отставание.

То же самое для карты, которая может закончиться, если вы попытаетесь вставить слишком много записей в карту.

Вопрос похож на "У меня есть локальная java.утиль.HashMap, что произойдет, если Я пытаюсь вставить в него 1 миллиард записей? что произойдет, если будет использована вся память". Так что не совсем то, что характерно для Hazelcast. Дайте мне знать, если я что-то упущу в вопросе.

- Талип

По умолчанию Hazelcast немедленно завершает работу узла, у которого заканчивается память. СмотритеDefaultOutOfMemoryHandler .

Если вы хотите изменить поведение по умолчанию, вы можете реализовать OutOfMemoryHandler

public class MyOutOfMemoryHandler extends OutOfMemoryHandler {

     public void onOutOfMemory(OutOfMemoryError oom, HazelcastInstance[] instances) {
        // handle oom
    }
}

И зарегистрировать его через

Hazelcast.setOutOfMemoryHandler(new MyOutOfMemoryHandler());