From 418f1b1494fc98380dfea559d48386f1ee9e6dcf Mon Sep 17 00:00:00 2001 From: Patrick Strawderman Date: Mon, 6 Mar 2023 13:57:20 -0800 Subject: [PATCH] Call size method on Application to avoid copying instance info DiscoveryClient called getInstancesAsIsFromEureka in a couple locations to get the number of instances for an application, when Application already has a method for this purpose that doesn't also incur the overhead of defensively copying. Additionally, fix a concurrency bug in Application.size, as it was accessing the underlying instances field without synchronization. --- .../src/main/java/com/netflix/discovery/DiscoveryClient.java | 4 ++-- .../main/java/com/netflix/discovery/shared/Application.java | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/eureka-client/src/main/java/com/netflix/discovery/DiscoveryClient.java b/eureka-client/src/main/java/com/netflix/discovery/DiscoveryClient.java index 4f22e5bce6..9d9e9d06c1 100644 --- a/eureka-client/src/main/java/com/netflix/discovery/DiscoveryClient.java +++ b/eureka-client/src/main/java/com/netflix/discovery/DiscoveryClient.java @@ -1115,7 +1115,7 @@ private void logTotalInstances() { if (logger.isDebugEnabled()) { int totInstances = 0; for (Application application : getApplications().getRegisteredApplications()) { - totInstances += application.getInstancesAsIsFromEureka().size(); + totInstances += application.size(); } logger.debug("The total number of all instances in the client now is {}", totInstances); } @@ -1219,7 +1219,7 @@ private void updateDelta(Applications delta) { * We find all instance list from application(The status of instance status is not only the status is UP but also other status) * if instance list is empty, we remove the application. */ - if (existingApp.getInstancesAsIsFromEureka().isEmpty()) { + if (existingApp.size() == 0) { applications.removeApplication(existingApp); } } diff --git a/eureka-client/src/main/java/com/netflix/discovery/shared/Application.java b/eureka-client/src/main/java/com/netflix/discovery/shared/Application.java index 57a5c21ec4..2598cc57f0 100644 --- a/eureka-client/src/main/java/com/netflix/discovery/shared/Application.java +++ b/eureka-client/src/main/java/com/netflix/discovery/shared/Application.java @@ -187,7 +187,9 @@ public void setName(String name) { * @return the number of instances in this application */ public int size() { - return instances.size(); + synchronized (instances) { + return instances.size(); + } } /** @@ -252,6 +254,7 @@ private void _shuffleAndStoreInstances(boolean filterUpInstances, boolean indexB this.shuffledInstances.set(instanceInfoList); } + private void removeInstance(InstanceInfo i, boolean markAsDirty) { instancesMap.remove(i.getId()); synchronized (instances) {