diff --git a/bundles/org.openhab.core.model.thing/src/org/openhab/core/model/thing/internal/GenericItemChannelLinkProvider.java b/bundles/org.openhab.core.model.thing/src/org/openhab/core/model/thing/internal/GenericItemChannelLinkProvider.java index 80517a38ea7..96546d788dd 100644 --- a/bundles/org.openhab.core.model.thing/src/org/openhab/core/model/thing/internal/GenericItemChannelLinkProvider.java +++ b/bundles/org.openhab.core.model.thing/src/org/openhab/core/model/thing/internal/GenericItemChannelLinkProvider.java @@ -13,6 +13,7 @@ package org.openhab.core.model.thing.internal; import java.util.Collection; +import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; @@ -45,7 +46,7 @@ public class GenericItemChannelLinkProvider extends AbstractProvider> itemChannelLinkMap = new ConcurrentHashMap<>(); + protected Map> itemChannelLinkMap = new ConcurrentHashMap<>(); /** * stores information about the context of items. The map has this content @@ -98,15 +99,20 @@ private void createItemChannelLink(String context, String itemName, String chann previousItemNames.remove(itemName); } - Set links = itemChannelLinkMap.get(itemName); + Map links = itemChannelLinkMap.get(itemName); if (links == null) { - itemChannelLinkMap.put(itemName, links = new HashSet<>()); + // Create a HashMap with an initial capacity of 2 (the default is 16) to save memory + // because most items have only one channel. A capacity of 2 is enough to avoid + // resizing the HashMap in most cases, whereas 1 would trigger a resize as soon as + // one element is added. + itemChannelLinkMap.put(itemName, links = new HashMap<>(2)); } - if (!links.contains(itemChannelLink)) { - links.add(itemChannelLink); + + ItemChannelLink oldLink = links.put(channelUIDObject, itemChannelLink); + if (oldLink == null) { notifyListenersAboutAddedElement(itemChannelLink); } else { - notifyListenersAboutUpdatedElement(itemChannelLink, itemChannelLink); + notifyListenersAboutUpdatedElement(oldLink, itemChannelLink); } } @@ -128,11 +134,9 @@ public void stopConfigurationUpdate(String context) { } for (String itemName : previousItemNames) { // we remove all binding configurations that were not processed - Set links = itemChannelLinkMap.remove(itemName); + Map links = itemChannelLinkMap.remove(itemName); if (links != null) { - for (ItemChannelLink removedItemChannelLink : links) { - notifyListenersAboutRemovedElement(removedItemChannelLink); - } + links.values().forEach(this::notifyListenersAboutRemovedElement); } } Optional.ofNullable(contextMap.get(context)).ifPresent(ctx -> ctx.removeAll(previousItemNames)); @@ -140,6 +144,6 @@ public void stopConfigurationUpdate(String context) { @Override public Collection getAll() { - return itemChannelLinkMap.values().stream().flatMap(Collection::stream).toList(); + return itemChannelLinkMap.values().stream().flatMap(m -> m.values().stream()).toList(); } }