You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by jb...@apache.org on 2019/04/10 19:33:32 UTC
[geode] branch develop updated: GEODE-6580: Cleanup static analyzer
warnings. (#3415)
This is an automated email from the ASF dual-hosted git repository.
jbarrett pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git
The following commit(s) were added to refs/heads/develop by this push:
new 80a32b1 GEODE-6580: Cleanup static analyzer warnings. (#3415)
80a32b1 is described below
commit 80a32b19c3cdbfe75c37d7b70104ea708739d2cd
Author: Jacob Barrett <jb...@pivotal.io>
AuthorDate: Wed Apr 10 12:33:16 2019 -0700
GEODE-6580: Cleanup static analyzer warnings. (#3415)
---
.../cache/client/internal/EndpointManagerImpl.java | 50 +-
.../internal/ClusterDistributionManager.java | 786 ++++++++++-----------
.../distributed/internal/DistributionAdvisor.java | 129 ++--
.../geode/internal/InternalInstantiator.java | 463 +++++-------
.../java/org/apache/geode/internal/SetUtils.java | 70 --
.../apache/geode/internal/cache/BucketAdvisor.java | 717 ++++++++-----------
.../apache/geode/internal/cache/BucketRegion.java | 554 ++++++---------
.../internal/cache/CacheDistributionAdvisor.java | 569 ++++++---------
.../geode/internal/cache/DistributedRegion.java | 768 ++++++++++----------
.../geode/internal/cache/GemFireCacheImpl.java | 10 +-
.../apache/geode/internal/cache/ImageState.java | 3 +-
.../apache/geode/internal/cache/LocalRegion.java | 5 +-
.../cache/PartitionedRegionBucketMgmtHelper.java | 11 +-
.../geode/internal/cache/UnsharedImageState.java | 106 ++-
.../geode/internal/cache/partitioned/Bucket.java | 4 +-
.../internal/cache/partitioned/RegionAdvisor.java | 351 +++++----
16 files changed, 1979 insertions(+), 2617 deletions(-)
diff --git a/geode-core/src/main/java/org/apache/geode/cache/client/internal/EndpointManagerImpl.java b/geode-core/src/main/java/org/apache/geode/cache/client/internal/EndpointManagerImpl.java
index 01d702d..e9f552d 100644
--- a/geode-core/src/main/java/org/apache/geode/cache/client/internal/EndpointManagerImpl.java
+++ b/geode-core/src/main/java/org/apache/geode/cache/client/internal/EndpointManagerImpl.java
@@ -12,6 +12,7 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
+
package org.apache.geode.cache.client.internal;
import java.util.ArrayList;
@@ -54,12 +55,6 @@ public class EndpointManagerImpl implements EndpointManager {
listener.addListener(new EndpointListenerForBridgeMembership());
}
- /*
- * (non-Javadoc)
- *
- * @see org.apache.geode.cache.client.internal.EndpointManager#referenceEndpoint(org.apache.geode.
- * distributed.internal.ServerLocation)
- */
@Override
public Endpoint referenceEndpoint(ServerLocation server, DistributedMember memberId) {
Endpoint endpoint = endpointMap.get(server);
@@ -89,13 +84,6 @@ public class EndpointManagerImpl implements EndpointManager {
return endpoint;
}
- /*
- * (non-Javadoc)
- *
- * @see
- * org.apache.geode.cache.client.internal.EndpointManager#serverCrashed(org.apache.geode.cache.
- * client.internal.Endpoint)
- */
@Override
public void serverCrashed(Endpoint endpoint) {
removeEndpoint(endpoint, true);
@@ -119,7 +107,7 @@ public class EndpointManagerImpl implements EndpointManager {
poolStats.setServerCount(endpointMap.size());
}
if (removedEndpoint) {
- PoolImpl pool = (PoolImpl) PoolManager.find(this.poolName);
+ PoolImpl pool = (PoolImpl) PoolManager.find(poolName);
if (pool != null && pool.getMultiuserAuthentication()) {
int size = 0;
ArrayList<ProxyCache> proxyCaches = pool.getProxyCacheList();
@@ -164,21 +152,11 @@ public class EndpointManagerImpl implements EndpointManager {
- /*
- * (non-Javadoc)
- *
- * @see org.apache.geode.cache.client.internal.EndpointManager#getEndpointMap()
- */
@Override
public Map<ServerLocation, Endpoint> getEndpointMap() {
return endpointMap;
}
- /*
- * (non-Javadoc)
- *
- * @see org.apache.geode.cache.client.internal.EndpointManager#close()
- */
@Override
public synchronized void close() {
for (ConnectionStats stats : statMap.values()) {
@@ -190,24 +168,11 @@ public class EndpointManagerImpl implements EndpointManager {
listener.clear();
}
- /*
- * (non-Javadoc)
- *
- * @see org.apache.geode.cache.client.internal.EndpointManager#addListener(org.apache.geode.cache.
- * client.internal.EndpointManagerImpl.EndpointListener)
- */
@Override
public void addListener(EndpointManager.EndpointListener listener) {
this.listener.addListener(listener);
}
- /*
- * (non-Javadoc)
- *
- * @see
- * org.apache.geode.cache.client.internal.EndpointManager#removeListener(org.apache.geode.cache.
- * client.internal.EndpointManagerImpl.EndpointListener)
- */
@Override
public void removeListener(EndpointManager.EndpointListener listener) {
this.listener.removeListener(listener);
@@ -217,17 +182,15 @@ public class EndpointManagerImpl implements EndpointManager {
ConnectionStats stats = statMap.get(location);
if (stats == null) {
String statName = poolName + "-" + location.toString();
- PoolImpl pool = (PoolImpl) PoolManager.find(this.poolName);
+ PoolImpl pool = (PoolImpl) PoolManager.find(poolName);
if (pool != null) {
if (pool.getGatewaySender() != null) {
stats = new ConnectionStats(new DummyStatisticsFactory(), statName,
- this.poolStats/* , this.gatewayStats */);
+ poolStats/* , this.gatewayStats */);
}
}
if (stats == null) {
- stats = new ConnectionStats(ds, statName, this.poolStats/*
- * , this.gatewayStats
- */);
+ stats = new ConnectionStats(ds, statName, poolStats);
}
statMap.put(location, stats);
}
@@ -251,8 +214,7 @@ public class EndpointManagerImpl implements EndpointManager {
protected static class EndpointListenerBroadcaster implements EndpointManager.EndpointListener {
- private volatile Set/* <EndpointListener> */<EndpointListener> endpointListeners =
- Collections.emptySet();
+ private volatile Set<EndpointListener> endpointListeners = Collections.emptySet();
public synchronized void addListener(EndpointManager.EndpointListener listener) {
HashSet<EndpointListener> tmpListeners = new HashSet<>(endpointListeners);
diff --git a/geode-core/src/main/java/org/apache/geode/distributed/internal/ClusterDistributionManager.java b/geode-core/src/main/java/org/apache/geode/distributed/internal/ClusterDistributionManager.java
index 9c14fd7..a8d1c08 100644
--- a/geode-core/src/main/java/org/apache/geode/distributed/internal/ClusterDistributionManager.java
+++ b/geode-core/src/main/java/org/apache/geode/distributed/internal/ClusterDistributionManager.java
@@ -12,12 +12,14 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
+
package org.apache.geode.distributed.internal;
import java.io.NotSerializableException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
@@ -68,7 +70,6 @@ import org.apache.geode.distributed.internal.membership.NetView;
import org.apache.geode.internal.Assert;
import org.apache.geode.internal.NanoTimer;
import org.apache.geode.internal.OSProcess;
-import org.apache.geode.internal.SetUtils;
import org.apache.geode.internal.Version;
import org.apache.geode.internal.admin.remote.AdminConsoleDisconnectMessage;
import org.apache.geode.internal.admin.remote.RemoteGfManagerAgent;
@@ -112,7 +113,7 @@ public class ClusterDistributionManager implements DistributionManager {
private static final Logger logger = LogService.getLogger();
private static final int STARTUP_TIMEOUT =
- Integer.getInteger("DistributionManager.STARTUP_TIMEOUT", 15000).intValue();
+ Integer.getInteger("DistributionManager.STARTUP_TIMEOUT", 15000);
private static final boolean DEBUG_NO_ACKNOWLEDGEMENTS =
Boolean.getBoolean("DistributionManager.DEBUG_NO_ACKNOWLEDGEMENTS");
@@ -144,57 +145,56 @@ public class ClusterDistributionManager implements DistributionManager {
!Boolean.getBoolean("DistributionManager.singleSerialExecutor");
private static final int MAX_WAITING_THREADS =
- Integer.getInteger("DistributionManager.MAX_WAITING_THREADS", Integer.MAX_VALUE).intValue();
+ Integer.getInteger("DistributionManager.MAX_WAITING_THREADS", Integer.MAX_VALUE);
private static final int MAX_PR_META_DATA_CLEANUP_THREADS =
- Integer.getInteger("DistributionManager.MAX_PR_META_DATA_CLEANUP_THREADS", 1).intValue();
+ Integer.getInteger("DistributionManager.MAX_PR_META_DATA_CLEANUP_THREADS", 1);
public static final int MAX_THREADS =
- Integer.getInteger("DistributionManager.MAX_THREADS", 100).intValue();
+ Integer.getInteger("DistributionManager.MAX_THREADS", 100);
private static final int MAX_PR_THREADS = Integer.getInteger("DistributionManager.MAX_PR_THREADS",
- Math.max(Runtime.getRuntime().availableProcessors() * 4, 16)).intValue();
+ Math.max(Runtime.getRuntime().availableProcessors() * 4, 16));
public static final int MAX_FE_THREADS = Integer.getInteger("DistributionManager.MAX_FE_THREADS",
- Math.max(Runtime.getRuntime().availableProcessors() * 4, 16)).intValue();
+ Math.max(Runtime.getRuntime().availableProcessors() * 4, 16));
private static final int INCOMING_QUEUE_LIMIT =
- Integer.getInteger("DistributionManager.INCOMING_QUEUE_LIMIT", 80000).intValue();
+ Integer.getInteger("DistributionManager.INCOMING_QUEUE_LIMIT", 80000);
/** Throttling based on the Queue byte size */
private static final double THROTTLE_PERCENT = (double) (Integer
- .getInteger("DistributionManager.SERIAL_QUEUE_THROTTLE_PERCENT", 75).intValue()) / 100;
+ .getInteger("DistributionManager.SERIAL_QUEUE_THROTTLE_PERCENT", 75)) / 100;
- static final int SERIAL_QUEUE_BYTE_LIMIT = Integer
- .getInteger("DistributionManager.SERIAL_QUEUE_BYTE_LIMIT", (40 * (1024 * 1024))).intValue();
+ private static final int SERIAL_QUEUE_BYTE_LIMIT = Integer
+ .getInteger("DistributionManager.SERIAL_QUEUE_BYTE_LIMIT", (40 * (1024 * 1024)));
- static final int SERIAL_QUEUE_THROTTLE =
+ private static final int SERIAL_QUEUE_THROTTLE =
Integer.getInteger("DistributionManager.SERIAL_QUEUE_THROTTLE",
- (int) (SERIAL_QUEUE_BYTE_LIMIT * THROTTLE_PERCENT)).intValue();
+ (int) (SERIAL_QUEUE_BYTE_LIMIT * THROTTLE_PERCENT));
- static final int TOTAL_SERIAL_QUEUE_BYTE_LIMIT =
- Integer.getInteger("DistributionManager.TOTAL_SERIAL_QUEUE_BYTE_LIMIT", (80 * (1024 * 1024)))
- .intValue();
+ private static final int TOTAL_SERIAL_QUEUE_BYTE_LIMIT =
+ Integer.getInteger("DistributionManager.TOTAL_SERIAL_QUEUE_BYTE_LIMIT", (80 * (1024 * 1024)));
- static final int TOTAL_SERIAL_QUEUE_THROTTLE =
+ private static final int TOTAL_SERIAL_QUEUE_THROTTLE =
Integer.getInteger("DistributionManager.TOTAL_SERIAL_QUEUE_THROTTLE",
- (int) (SERIAL_QUEUE_BYTE_LIMIT * THROTTLE_PERCENT)).intValue();
+ (int) (SERIAL_QUEUE_BYTE_LIMIT * THROTTLE_PERCENT));
/** Throttling based on the Queue item size */
- static final int SERIAL_QUEUE_SIZE_LIMIT =
- Integer.getInteger("DistributionManager.SERIAL_QUEUE_SIZE_LIMIT", 20000).intValue();
+ private static final int SERIAL_QUEUE_SIZE_LIMIT =
+ Integer.getInteger("DistributionManager.SERIAL_QUEUE_SIZE_LIMIT", 20000);
- static final int SERIAL_QUEUE_SIZE_THROTTLE =
+ private static final int SERIAL_QUEUE_SIZE_THROTTLE =
Integer.getInteger("DistributionManager.SERIAL_QUEUE_SIZE_THROTTLE",
- (int) (SERIAL_QUEUE_SIZE_LIMIT * THROTTLE_PERCENT)).intValue();
+ (int) (SERIAL_QUEUE_SIZE_LIMIT * THROTTLE_PERCENT));
/** Max number of serial Queue executors, in case of multi-serial-queue executor */
- static final int MAX_SERIAL_QUEUE_THREAD =
- Integer.getInteger("DistributionManager.MAX_SERIAL_QUEUE_THREAD", 20).intValue();
+ private static final int MAX_SERIAL_QUEUE_THREAD =
+ Integer.getInteger("DistributionManager.MAX_SERIAL_QUEUE_THREAD", 20);
- protected static final String FUNCTION_EXECUTION_PROCESSOR_THREAD_PREFIX =
+ static final String FUNCTION_EXECUTION_PROCESSOR_THREAD_PREFIX =
"Function Execution Processor";
/** The DM type for regular distribution managers */
@@ -476,7 +476,7 @@ public class ClusterDistributionManager implements DistributionManager {
*/
private final HashMap<InetAddress, Set<InetAddress>> equivalentHosts = new HashMap<>();
- private int distributedSystemId = DistributionConfig.DEFAULT_DISTRIBUTED_SYSTEM_ID;
+ private int distributedSystemId;
private final Map<InternalDistributedMember, String> redundancyZones =
@@ -600,15 +600,14 @@ public class ClusterDistributionManager implements DistributionManager {
if (logger.isInfoEnabled()) {
long delta = System.currentTimeMillis() - start;
- Object[] logArgs = new Object[] {distributionManager.getDistributionManagerId(), transport,
- Integer.valueOf(distributionManager.getOtherDistributionManagerIds().size()),
+ logger.info(LogMarker.DM_MARKER,
+ "DistributionManager {} started on {}. There were {} other DMs. others: {} {} {}",
+ distributionManager.getDistributionManagerId(), transport,
+ distributionManager.getOtherDistributionManagerIds().size(),
distributionManager.getOtherDistributionManagerIds(),
(logger.isInfoEnabled(LogMarker.DM_MARKER) ? " (took " + delta + " ms)" : ""),
((distributionManager.getDMType() == ADMIN_ONLY_DM_TYPE) ? " (admin only)"
- : (distributionManager.getDMType() == LOCATOR_DM_TYPE) ? " (locator)" : "")};
- logger.info(LogMarker.DM_MARKER,
- "DistributionManager {} started on {}. There were {} other DMs. others: {} {} {}",
- logArgs);
+ : (distributionManager.getDMType() == LOCATOR_DM_TYPE) ? " (locator)" : ""));
MembershipLogger.logStartup(distributionManager.getDistributionManagerId());
}
@@ -636,29 +635,29 @@ public class ClusterDistributionManager implements DistributionManager {
private ClusterDistributionManager(RemoteTransportConfig transport,
InternalDistributedSystem system, AlertingService alertingService) {
- this.dmType = transport.getVmKind();
this.system = system;
this.transport = transport;
this.alertingService = alertingService;
- this.membershipListeners = new ConcurrentHashMap<>();
- this.distributedSystemId = system.getConfig().getDistributedSystemId();
+ dmType = transport.getVmKind();
+ membershipListeners = new ConcurrentHashMap<>();
+ distributedSystemId = system.getConfig().getDistributedSystemId();
long statId = OSProcess.getId();
- this.stats = new DistributionStats(system, statId);
+ stats = new DistributionStats(system, statId);
DistributionStats.enableClockStats = system.getConfig().getEnableTimeStatistics();
- this.exceptionInThreads = false;
+ exceptionInThreads = false;
{
Properties nonDefault = new Properties();
DistributionConfigImpl distributionConfigImpl = new DistributionConfigImpl(nonDefault);
if (distributionConfigImpl.getThreadMonitorEnabled()) {
- this.threadMonitor = new ThreadsMonitoringImpl(system);
+ threadMonitor = new ThreadsMonitoringImpl(system);
logger.info("[ThreadsMonitor] a New Monitor object and process were created.\n");
} else {
- this.threadMonitor = new ThreadsMonitoringImplDummy();
+ threadMonitor = new ThreadsMonitoringImplDummy();
logger.info("[ThreadsMonitor] Monitoring is disabled and will not be run.\n");
}
}
@@ -680,44 +679,44 @@ public class ClusterDistributionManager implements DistributionManager {
// when TCP/IP is disabled we can't throttle the serial queue or we run the risk of
// distributed deadlock when we block the UDP reader thread
boolean throttlingDisabled = system.getConfig().getDisableTcp();
- this.serialQueuedExecutorPool =
- new SerialQueuedExecutorPool(this.stats, throttlingDisabled, this.threadMonitor);
+ serialQueuedExecutorPool =
+ new SerialQueuedExecutorPool(stats, throttlingDisabled, threadMonitor);
}
{
- BlockingQueue poolQueue;
+ BlockingQueue<Runnable> poolQueue;
if (SERIAL_QUEUE_BYTE_LIMIT == 0) {
- poolQueue = new OverflowQueueWithDMStats(this.stats.getSerialQueueHelper());
+ poolQueue = new OverflowQueueWithDMStats<>(stats.getSerialQueueHelper());
} else {
- this.serialQueue =
+ serialQueue =
new ThrottlingMemLinkedQueueWithDMStats<>(TOTAL_SERIAL_QUEUE_BYTE_LIMIT,
TOTAL_SERIAL_QUEUE_THROTTLE, SERIAL_QUEUE_SIZE_LIMIT, SERIAL_QUEUE_SIZE_THROTTLE,
- this.stats.getSerialQueueHelper());
- poolQueue = this.serialQueue;
+ stats.getSerialQueueHelper());
+ poolQueue = serialQueue;
}
- this.serialThread = LoggingExecutors.newSerialThreadPool("Serial Message Processor",
+ serialThread = LoggingExecutors.newSerialThreadPool("Serial Message Processor",
thread -> stats.incSerialThreadStarts(),
- this::doSerialThread, this.stats.getSerialProcessorHelper(),
+ this::doSerialThread, stats.getSerialProcessorHelper(),
threadMonitor, poolQueue);
}
- this.viewThread =
+ viewThread =
LoggingExecutors.newSerialThreadPoolWithUnlimitedFeed("View Message Processor",
thread -> stats.incViewThreadStarts(), this::doViewThread,
- this.stats.getViewProcessorHelper(), threadMonitor);
+ stats.getViewProcessorHelper(), threadMonitor);
- this.threadPool =
+ threadPool =
LoggingExecutors.newThreadPoolWithFeedStatistics("Pooled Message Processor ",
thread -> stats.incProcessingThreadStarts(), this::doProcessingThread,
- MAX_THREADS, this.stats.getNormalPoolHelper(), threadMonitor,
- INCOMING_QUEUE_LIMIT, this.stats.getOverflowQueueHelper());
+ MAX_THREADS, stats.getNormalPoolHelper(), threadMonitor,
+ INCOMING_QUEUE_LIMIT, stats.getOverflowQueueHelper());
- this.highPriorityPool = LoggingExecutors.newThreadPoolWithFeedStatistics(
+ highPriorityPool = LoggingExecutors.newThreadPoolWithFeedStatistics(
"Pooled High Priority Message Processor ",
thread -> stats.incHighPriorityThreadStarts(), this::doHighPriorityThread,
- MAX_THREADS, this.stats.getHighPriorityPoolHelper(), threadMonitor,
- INCOMING_QUEUE_LIMIT, this.stats.getHighPriorityQueueHelper());
+ MAX_THREADS, stats.getHighPriorityPoolHelper(), threadMonitor,
+ INCOMING_QUEUE_LIMIT, stats.getHighPriorityQueueHelper());
{
BlockingQueue<Runnable> poolQueue;
@@ -725,55 +724,55 @@ public class ClusterDistributionManager implements DistributionManager {
// no need for a queue since we have infinite threads
poolQueue = new SynchronousQueue<>();
} else {
- poolQueue = new OverflowQueueWithDMStats<>(this.stats.getWaitingQueueHelper());
+ poolQueue = new OverflowQueueWithDMStats<>(stats.getWaitingQueueHelper());
}
- this.waitingPool = LoggingExecutors.newThreadPool("Pooled Waiting Message Processor ",
+ waitingPool = LoggingExecutors.newThreadPool("Pooled Waiting Message Processor ",
thread -> stats.incWaitingThreadStarts(), this::doWaitingThread,
- MAX_WAITING_THREADS, this.stats.getWaitingPoolHelper(), threadMonitor, poolQueue);
+ MAX_WAITING_THREADS, stats.getWaitingPoolHelper(), threadMonitor, poolQueue);
}
// should this pool using the waiting pool stats?
- this.prMetaDataCleanupThreadPool =
+ prMetaDataCleanupThreadPool =
LoggingExecutors.newThreadPoolWithFeedStatistics("PrMetaData cleanup Message Processor ",
thread -> stats.incWaitingThreadStarts(), this::doWaitingThread,
- MAX_PR_META_DATA_CLEANUP_THREADS, this.stats.getWaitingPoolHelper(), threadMonitor,
- 0, this.stats.getWaitingQueueHelper());
+ MAX_PR_META_DATA_CLEANUP_THREADS, stats.getWaitingPoolHelper(), threadMonitor,
+ 0, stats.getWaitingQueueHelper());
if (MAX_PR_THREADS > 1) {
- this.partitionedRegionPool =
+ partitionedRegionPool =
LoggingExecutors.newThreadPoolWithFeedStatistics("PartitionedRegion Message Processor",
thread -> stats.incPartitionedRegionThreadStarts(), this::doPartitionRegionThread,
- MAX_PR_THREADS, this.stats.getPartitionedRegionPoolHelper(), threadMonitor,
- INCOMING_QUEUE_LIMIT, this.stats.getPartitionedRegionQueueHelper());
+ MAX_PR_THREADS, stats.getPartitionedRegionPoolHelper(), threadMonitor,
+ INCOMING_QUEUE_LIMIT, stats.getPartitionedRegionQueueHelper());
} else {
- this.partitionedRegionThread = LoggingExecutors.newSerialThreadPoolWithFeedStatistics(
+ partitionedRegionThread = LoggingExecutors.newSerialThreadPoolWithFeedStatistics(
"PartitionedRegion Message Processor",
thread -> stats.incPartitionedRegionThreadStarts(), this::doPartitionRegionThread,
- this.stats.getPartitionedRegionPoolHelper(), threadMonitor,
- INCOMING_QUEUE_LIMIT, this.stats.getPartitionedRegionQueueHelper());
+ stats.getPartitionedRegionPoolHelper(), threadMonitor,
+ INCOMING_QUEUE_LIMIT, stats.getPartitionedRegionQueueHelper());
}
if (MAX_FE_THREADS > 1) {
- this.functionExecutionPool =
+ functionExecutionPool =
LoggingExecutors.newFunctionThreadPoolWithFeedStatistics(
FUNCTION_EXECUTION_PROCESSOR_THREAD_PREFIX,
thread -> stats.incFunctionExecutionThreadStarts(), this::doFunctionExecutionThread,
- MAX_FE_THREADS, this.stats.getFunctionExecutionPoolHelper(), threadMonitor,
- INCOMING_QUEUE_LIMIT, this.stats.getFunctionExecutionQueueHelper());
+ MAX_FE_THREADS, stats.getFunctionExecutionPoolHelper(), threadMonitor,
+ INCOMING_QUEUE_LIMIT, stats.getFunctionExecutionQueueHelper());
} else {
- this.functionExecutionThread =
+ functionExecutionThread =
LoggingExecutors.newSerialThreadPoolWithFeedStatistics(
FUNCTION_EXECUTION_PROCESSOR_THREAD_PREFIX,
thread -> stats.incFunctionExecutionThreadStarts(), this::doFunctionExecutionThread,
- this.stats.getFunctionExecutionPoolHelper(), threadMonitor,
- INCOMING_QUEUE_LIMIT, this.stats.getFunctionExecutionQueueHelper());
+ stats.getFunctionExecutionPoolHelper(), threadMonitor,
+ INCOMING_QUEUE_LIMIT, stats.getFunctionExecutionQueueHelper());
}
if (!SYNC_EVENTS) {
- this.memberEventThread =
+ memberEventThread =
new LoggingThread("DM-MemberEventInvoker", new MemberEventInvoker());
}
- StringBuffer sb = new StringBuffer(" (took ");
+ StringBuilder sb = new StringBuilder(" (took ");
// connect to the cluster
long start = System.currentTimeMillis();
@@ -784,17 +783,17 @@ public class ClusterDistributionManager implements DistributionManager {
sb.append(System.currentTimeMillis() - start);
- this.localAddress = membershipManager.getLocalMember();
+ localAddress = membershipManager.getLocalMember();
membershipManager.postConnect();
sb.append(" ms)");
logger.info("Starting DistributionManager {}. {}",
- new Object[] {this.localAddress,
+ new Object[] {localAddress,
(logger.isInfoEnabled(LogMarker.DM_MARKER) ? sb.toString() : "")});
- this.description = "Distribution manager on " + this.localAddress + " started at "
+ description = "Distribution manager on " + localAddress + " started at "
+ (new Date(System.currentTimeMillis())).toString();
finishedConstructor = true;
@@ -902,14 +901,14 @@ public class ClusterDistributionManager implements DistributionManager {
boolean finishedConstructor = false;
try {
- setIsStartupThread(Boolean.TRUE);
+ setIsStartupThread();
startThreads();
// Allow events to start being processed.
membershipManager.startEventProcessing();
for (;;) {
- this.getCancelCriterion().checkCancelInProgress(null);
+ getCancelCriterion().checkCancelInProgress(null);
boolean interrupted = Thread.interrupted();
try {
membershipManager.waitForEventProcessing();
@@ -945,12 +944,12 @@ public class ClusterDistributionManager implements DistributionManager {
ClusterDistributionManager.isDedicatedAdminVM = isDedicatedAdminVM;
}
- private static Boolean getIsStartupThread() {
+ private static Boolean isStartupThread() {
return isStartupThread.get();
}
- private static void setIsStartupThread(Boolean isStartup) {
- ClusterDistributionManager.isStartupThread.set(isStartup);
+ private static void setIsStartupThread() {
+ ClusterDistributionManager.isStartupThread.set(Boolean.TRUE);
}
//////////////////// Instance Methods /////////////////////
@@ -1029,7 +1028,7 @@ public class ClusterDistributionManager implements DistributionManager {
void setRedundancyZone(InternalDistributedMember member, String redundancyZone) {
if (redundancyZone != null && !redundancyZone.equals("")) {
- this.redundancyZones.put(member, redundancyZone);
+ redundancyZones.put(member, redundancyZone);
}
if (member != getDistributionManagerId()) {
String relationship = areInSameZone(getDistributionManagerId(), member) ? "" : "not ";
@@ -1084,7 +1083,7 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public int getDMType() {
- return this.dmType;
+ return dmType;
}
@Override
@@ -1093,16 +1092,16 @@ public class ClusterDistributionManager implements DistributionManager {
}
private boolean testMulticast() {
- return this.membershipManager.testMulticast();
+ return membershipManager.testMulticast();
}
/**
* Need to do this outside the constructor so that the child constructor can finish.
*/
private void startThreads() {
- this.system.setDM(this); // fix for bug 33362
- if (this.memberEventThread != null)
- this.memberEventThread.start();
+ system.setDM(this); // fix for bug 33362
+ if (memberEventThread != null)
+ memberEventThread.start();
try {
// And the distinguished guests today are...
@@ -1121,14 +1120,11 @@ public class ClusterDistributionManager implements DistributionManager {
ex);
}
try {
- getWaitingThreadPool().execute(new Runnable() {
- @Override
- public void run() {
- // call in background since it might need to send a reply
- // and we are not ready to send messages until startup is finished
- setIsStartupThread(Boolean.TRUE);
- readyForMessages();
- }
+ getWaitingThreadPool().execute(() -> {
+ // call in background since it might need to send a reply
+ // and we are not ready to send messages until startup is finished
+ setIsStartupThread();
+ readyForMessages();
});
} catch (VirtualMachineError err) {
SystemFailure.initiateFailure(err);
@@ -1148,8 +1144,8 @@ public class ClusterDistributionManager implements DistributionManager {
private void readyForMessages() {
synchronized (this) {
- this.readyForMessages = true;
- this.notifyAll();
+ readyForMessages = true;
+ notifyAll();
}
membershipManager.startEventProcessing();
}
@@ -1162,7 +1158,7 @@ public class ClusterDistributionManager implements DistributionManager {
stopper.checkCancelInProgress(null);
boolean interrupted = Thread.interrupted();
try {
- this.wait();
+ wait();
} catch (InterruptedException e) {
interrupted = true;
stopper.checkCancelInProgress(e);
@@ -1179,9 +1175,9 @@ public class ClusterDistributionManager implements DistributionManager {
* Call when the DM is ready to send messages.
*/
private void readyToSendMsgs() {
- synchronized (this.readyToSendMsgsLock) {
- this.readyToSendMsgs = true;
- this.readyToSendMsgsLock.notifyAll();
+ synchronized (readyToSendMsgsLock) {
+ readyToSendMsgs = true;
+ readyToSendMsgsLock.notifyAll();
}
}
@@ -1191,28 +1187,27 @@ public class ClusterDistributionManager implements DistributionManager {
* @param msg the messsage that is currently being sent
*/
private void waitUntilReadyToSendMsgs(DistributionMessage msg) {
- if (this.readyToSendMsgs) {
+ if (readyToSendMsgs) {
return;
}
// another process may have been started in the same view, so we need
// to be responsive to startup messages and be able to send responses
- if (msg instanceof StartupMessage || msg instanceof StartupResponseMessage
- || msg instanceof AdminMessageType) {
+ if (msg instanceof AdminMessageType) {
return;
}
- if (getIsStartupThread() == Boolean.TRUE) {
+ if (isStartupThread() == Boolean.TRUE) {
// let the startup thread send messages
// the only case I know of that does this is if we happen to log a
// message during startup and an alert listener has registered.
return;
}
- synchronized (this.readyToSendMsgsLock) {
- while (!this.readyToSendMsgs) {
+ synchronized (readyToSendMsgsLock) {
+ while (!readyToSendMsgs) {
stopper.checkCancelInProgress(null);
boolean interrupted = Thread.interrupted();
try {
- this.readyToSendMsgsLock.wait();
+ readyToSendMsgsLock.wait();
} catch (InterruptedException e) {
interrupted = true;
stopper.checkCancelInProgress(e);
@@ -1242,7 +1237,7 @@ public class ClusterDistributionManager implements DistributionManager {
*/
@Override
public boolean exceptionInThreads() {
- return this.exceptionInThreads
+ return exceptionInThreads
|| LoggingUncaughtExceptionHandler.getUncaughtExceptionsCount() > 0;
}
@@ -1252,7 +1247,7 @@ public class ClusterDistributionManager implements DistributionManager {
*/
@Override
public void clearExceptionInThreads() {
- this.exceptionInThreads = false;
+ exceptionInThreads = false;
LoggingUncaughtExceptionHandler.clearUncaughtExceptionsCount();
}
@@ -1262,7 +1257,7 @@ public class ClusterDistributionManager implements DistributionManager {
*/
@Override
public long cacheTimeMillis() {
- return this.system.getClock().cacheTimeMillis();
+ return system.getClock().cacheTimeMillis();
}
@@ -1273,7 +1268,7 @@ public class ClusterDistributionManager implements DistributionManager {
return id;
}
}
- if (Objects.equals(localAddress, name)) {
+ if (Objects.equals(localAddress.getName(), name)) {
return localAddress;
}
return null;
@@ -1284,7 +1279,7 @@ public class ClusterDistributionManager implements DistributionManager {
*/
@Override
public InternalDistributedMember getDistributionManagerId() {
- return this.localAddress;
+ return localAddress;
}
/**
@@ -1295,8 +1290,8 @@ public class ClusterDistributionManager implements DistributionManager {
public Set<InternalDistributedMember> getDistributionManagerIds() {
// access to members synchronized under membersLock in order to
// ensure serialization
- synchronized (this.membersLock) {
- return this.members.keySet();
+ synchronized (membersLock) {
+ return members.keySet();
}
}
@@ -1310,29 +1305,29 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public void addHostedLocators(InternalDistributedMember member, Collection<String> locators,
boolean isSharedConfigurationEnabled) {
- synchronized (this.membersLock) {
+ synchronized (membersLock) {
if (locators == null || locators.isEmpty()) {
throw new IllegalArgumentException("Cannot use empty collection of locators");
}
- if (this.hostedLocatorsAll.isEmpty()) {
- this.hostedLocatorsAll = new HashMap<>();
+ if (hostedLocatorsAll.isEmpty()) {
+ hostedLocatorsAll = new HashMap<>();
}
Map<InternalDistributedMember, Collection<String>> tmp =
- new HashMap<>(this.hostedLocatorsAll);
+ new HashMap<>(hostedLocatorsAll);
tmp.remove(member);
tmp.put(member, locators);
tmp = Collections.unmodifiableMap(tmp);
- this.hostedLocatorsAll = tmp;
+ hostedLocatorsAll = tmp;
if (isSharedConfigurationEnabled) {
- if (this.hostedLocatorsWithSharedConfiguration.isEmpty()) {
- this.hostedLocatorsWithSharedConfiguration = new HashMap<>();
+ if (hostedLocatorsWithSharedConfiguration.isEmpty()) {
+ hostedLocatorsWithSharedConfiguration = new HashMap<>();
}
- tmp = new HashMap<>(this.hostedLocatorsWithSharedConfiguration);
+ tmp = new HashMap<>(hostedLocatorsWithSharedConfiguration);
tmp.remove(member);
tmp.put(member, locators);
tmp = Collections.unmodifiableMap(tmp);
- this.hostedLocatorsWithSharedConfiguration = tmp;
+ hostedLocatorsWithSharedConfiguration = tmp;
}
}
@@ -1340,29 +1335,29 @@ public class ClusterDistributionManager implements DistributionManager {
private void removeHostedLocators(InternalDistributedMember member) {
- synchronized (this.membersLock) {
- if (this.hostedLocatorsAll.containsKey(member)) {
+ synchronized (membersLock) {
+ if (hostedLocatorsAll.containsKey(member)) {
Map<InternalDistributedMember, Collection<String>> tmp =
- new HashMap<>(this.hostedLocatorsAll);
+ new HashMap<>(hostedLocatorsAll);
tmp.remove(member);
if (tmp.isEmpty()) {
tmp = Collections.emptyMap();
} else {
tmp = Collections.unmodifiableMap(tmp);
}
- this.hostedLocatorsAll = tmp;
+ hostedLocatorsAll = tmp;
}
- if (this.hostedLocatorsWithSharedConfiguration.containsKey(member)) {
+ if (hostedLocatorsWithSharedConfiguration.containsKey(member)) {
Map<InternalDistributedMember, Collection<String>> tmp =
new HashMap<>(
- this.hostedLocatorsWithSharedConfiguration);
+ hostedLocatorsWithSharedConfiguration);
tmp.remove(member);
if (tmp.isEmpty()) {
tmp = Collections.emptyMap();
} else {
tmp = Collections.unmodifiableMap(tmp);
}
- this.hostedLocatorsWithSharedConfiguration = tmp;
+ hostedLocatorsWithSharedConfiguration = tmp;
}
}
}
@@ -1378,8 +1373,8 @@ public class ClusterDistributionManager implements DistributionManager {
*/
@Override
public Collection<String> getHostedLocators(InternalDistributedMember member) {
- synchronized (this.membersLock) {
- return this.hostedLocatorsAll.get(member);
+ synchronized (membersLock) {
+ return hostedLocatorsAll.get(member);
}
}
@@ -1400,8 +1395,8 @@ public class ClusterDistributionManager implements DistributionManager {
*/
@Override
public Map<InternalDistributedMember, Collection<String>> getAllHostedLocators() {
- synchronized (this.membersLock) {
- return this.hostedLocatorsAll;
+ synchronized (membersLock) {
+ return hostedLocatorsAll;
}
}
@@ -1414,8 +1409,8 @@ public class ClusterDistributionManager implements DistributionManager {
*/
@Override
public Map<InternalDistributedMember, Collection<String>> getAllHostedLocatorsWithSharedConfiguration() {
- synchronized (this.membersLock) {
- return this.hostedLocatorsWithSharedConfiguration;
+ synchronized (membersLock) {
+ return hostedLocatorsWithSharedConfiguration;
}
}
@@ -1427,8 +1422,8 @@ public class ClusterDistributionManager implements DistributionManager {
public Set<InternalDistributedMember> getDistributionManagerIdsIncludingAdmin() {
// access to members synchronized under membersLock in order to
// ensure serialization
- synchronized (this.membersLock) {
- return this.membersAndAdmin;
+ synchronized (membersLock) {
+ return membersAndAdmin;
}
}
@@ -1466,7 +1461,7 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public InternalDistributedMember getCanonicalId(DistributedMember id) {
// the members set is copy-on-write, so it is safe to iterate over it
- InternalDistributedMember result = this.members.get(id);
+ InternalDistributedMember result = members.get(id);
if (result == null) {
return (InternalDistributedMember) id;
}
@@ -1480,7 +1475,7 @@ public class ClusterDistributionManager implements DistributionManager {
public Set<InternalDistributedMember> addMembershipListenerAndGetDistributionManagerIds(
MembershipListener l) {
// switched sync order to fix bug 30360
- synchronized (this.membersLock) {
+ synchronized (membersLock) {
// Don't let the members come and go while we are adding this
// listener. This ensures that the listener (probably a
// ReplyProcessor) gets a consistent view of the members.
@@ -1504,7 +1499,7 @@ public class ClusterDistributionManager implements DistributionManager {
break;
default:
throw new InternalGemFireError(String.format("Unknown member type: %s",
- Integer.valueOf(vmType)));
+ vmType));
}
}
@@ -1513,7 +1508,7 @@ public class ClusterDistributionManager implements DistributionManager {
*/
@Override
public InternalDistributedMember getId() {
- return this.localAddress;
+ return localAddress;
}
@Override
@@ -1536,7 +1531,7 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public String toString() {
- return this.description;
+ return description;
}
/**
@@ -1549,20 +1544,20 @@ public class ClusterDistributionManager implements DistributionManager {
if (closeInProgress) {
return;
}
- this.closeInProgress = true;
+ closeInProgress = true;
} // synchronized
// [bruce] log shutdown at info level and with ID to balance the
// "Starting" message. recycleConn.conf is hard to debug w/o this
- final String exceptionStatus = (this.exceptionInThreads()
+ final String exceptionStatus = (exceptionInThreads()
? "At least one Exception occurred."
: "");
logger.info("Shutting down DistributionManager {}. {}",
- new Object[] {this.localAddress, exceptionStatus});
+ new Object[] {localAddress, exceptionStatus});
final long start = System.currentTimeMillis();
try {
- if (this.rootCause instanceof ForcedDisconnectException) {
+ if (rootCause instanceof ForcedDisconnectException) {
if (logger.isDebugEnabled()) {
logger.debug(
"inhibiting sending of shutdown message to other members due to forced-disconnect");
@@ -1570,21 +1565,18 @@ public class ClusterDistributionManager implements DistributionManager {
} else {
// Don't block indefinitely trying to send the shutdown message, in
// case other VMs in the system are ill-behaved. (bug 34710)
- final Runnable r = new Runnable() {
- @Override
- public void run() {
- try {
- ConnectionTable.threadWantsSharedResources();
- sendShutdownMessage();
- } catch (final CancelException e) {
- // We were terminated.
- logger.debug("Cancelled during shutdown message", e);
- }
+ final Runnable r = () -> {
+ try {
+ ConnectionTable.threadWantsSharedResources();
+ sendShutdownMessage();
+ } catch (final CancelException e) {
+ // We were terminated.
+ logger.debug("Cancelled during shutdown message", e);
}
};
final Thread t =
new LoggingThread(String.format("Shutdown Message Thread for %s",
- this.localAddress), false, r);
+ localAddress), false, r);
t.start();
boolean interrupted = Thread.interrupted();
try {
@@ -1607,11 +1599,11 @@ public class ClusterDistributionManager implements DistributionManager {
}
} finally {
- this.shutdownMsgSent = true; // in case sendShutdownMessage failed....
+ shutdownMsgSent = true; // in case sendShutdownMessage failed....
try {
- this.uncleanShutdown(false);
+ uncleanShutdown(false);
} finally {
- final Long delta = Long.valueOf(System.currentTimeMillis() - start);
+ final Long delta = System.currentTimeMillis() - start;
logger.info("DistributionManager stopped in {}ms.", delta);
}
}
@@ -1621,54 +1613,54 @@ public class ClusterDistributionManager implements DistributionManager {
// Stop executors after they have finished
ExecutorService es;
threadMonitor.close();
- es = this.serialThread;
+ es = serialThread;
if (es != null) {
es.shutdown();
}
- es = this.viewThread;
+ es = viewThread;
if (es != null) {
// Hmmm...OK, I'll let any view events currently in the queue be
// processed. Not sure it's very important whether they get
// handled...
es.shutdown();
}
- if (this.serialQueuedExecutorPool != null) {
- this.serialQueuedExecutorPool.shutdown();
+ if (serialQueuedExecutorPool != null) {
+ serialQueuedExecutorPool.shutdown();
}
- es = this.functionExecutionThread;
+ es = functionExecutionThread;
if (es != null) {
es.shutdown();
}
- es = this.functionExecutionPool;
+ es = functionExecutionPool;
if (es != null) {
es.shutdown();
}
- es = this.partitionedRegionThread;
+ es = partitionedRegionThread;
if (es != null) {
es.shutdown();
}
- es = this.partitionedRegionPool;
+ es = partitionedRegionPool;
if (es != null) {
es.shutdown();
}
- es = this.highPriorityPool;
+ es = highPriorityPool;
if (es != null) {
es.shutdown();
}
- es = this.waitingPool;
+ es = waitingPool;
if (es != null) {
es.shutdown();
}
- es = this.prMetaDataCleanupThreadPool;
+ es = prMetaDataCleanupThreadPool;
if (es != null) {
es.shutdown();
}
- es = this.threadPool;
+ es = threadPool;
if (es != null) {
es.shutdown();
}
- Thread th = this.memberEventThread;
+ Thread th = memberEventThread;
if (th != null)
th.interrupt();
}
@@ -1677,10 +1669,10 @@ public class ClusterDistributionManager implements DistributionManager {
long start = System.currentTimeMillis();
long remaining = timeInMillis;
- ExecutorService[] allExecutors = new ExecutorService[] {this.serialThread, this.viewThread,
- this.functionExecutionThread, this.functionExecutionPool, this.partitionedRegionThread,
- this.partitionedRegionPool, this.highPriorityPool, this.waitingPool,
- this.prMetaDataCleanupThreadPool, this.threadPool};
+ ExecutorService[] allExecutors = new ExecutorService[] {serialThread, viewThread,
+ functionExecutionThread, functionExecutionPool, partitionedRegionThread,
+ partitionedRegionPool, highPriorityPool, waitingPool,
+ prMetaDataCleanupThreadPool, threadPool};
for (ExecutorService es : allExecutors) {
if (es != null) {
es.awaitTermination(remaining, TimeUnit.MILLISECONDS);
@@ -1691,13 +1683,12 @@ public class ClusterDistributionManager implements DistributionManager {
}
}
-
- this.serialQueuedExecutorPool.awaitTermination(remaining, TimeUnit.MILLISECONDS);
+ serialQueuedExecutorPool.awaitTermination(remaining, TimeUnit.MILLISECONDS);
remaining = timeInMillis - (System.currentTimeMillis() - start);
if (remaining <= 0) {
return;
}
- Thread th = this.memberEventThread;
+ Thread th = memberEventThread;
if (th != null) {
th.interrupt(); // bug #43452 - this thread sometimes eats interrupts, so we interrupt it
// again here
@@ -1767,41 +1758,41 @@ public class ClusterDistributionManager implements DistributionManager {
*/
private void forceThreadsToStop() {
long endTime = System.currentTimeMillis() + MAX_STOP_TIME;
- String culprits = "";
+ StringBuilder culprits;
for (;;) {
boolean stillAlive = false;
- culprits = "";
- if (executorAlive(this.serialThread, "serial thread")) {
+ culprits = new StringBuilder();
+ if (executorAlive(serialThread, "serial thread")) {
stillAlive = true;
- culprits = culprits + " serial thread;";
+ culprits.append(" serial thread;");
}
- if (executorAlive(this.viewThread, "view thread")) {
+ if (executorAlive(viewThread, "view thread")) {
stillAlive = true;
- culprits = culprits + " view thread;";
+ culprits.append(" view thread;");
}
- if (executorAlive(this.partitionedRegionThread, "partitioned region thread")) {
+ if (executorAlive(partitionedRegionThread, "partitioned region thread")) {
stillAlive = true;
- culprits = culprits + " partitioned region thread;";
+ culprits.append(" partitioned region thread;");
}
- if (executorAlive(this.partitionedRegionPool, "partitioned region pool")) {
+ if (executorAlive(partitionedRegionPool, "partitioned region pool")) {
stillAlive = true;
- culprits = culprits + " partitioned region pool;";
+ culprits.append(" partitioned region pool;");
}
- if (executorAlive(this.highPriorityPool, "high priority pool")) {
+ if (executorAlive(highPriorityPool, "high priority pool")) {
stillAlive = true;
- culprits = culprits + " high priority pool;";
+ culprits.append(" high priority pool;");
}
- if (executorAlive(this.waitingPool, "waiting pool")) {
+ if (executorAlive(waitingPool, "waiting pool")) {
stillAlive = true;
- culprits = culprits + " waiting pool;";
+ culprits.append(" waiting pool;");
}
- if (executorAlive(this.prMetaDataCleanupThreadPool, "prMetaDataCleanupThreadPool")) {
+ if (executorAlive(prMetaDataCleanupThreadPool, "prMetaDataCleanupThreadPool")) {
stillAlive = true;
- culprits = culprits + " special waiting pool;";
+ culprits.append(" special waiting pool;");
}
- if (executorAlive(this.threadPool, "thread pool")) {
+ if (executorAlive(threadPool, "thread pool")) {
stillAlive = true;
- culprits = culprits + " thread pool;";
+ culprits.append(" thread pool;");
}
if (!stillAlive)
@@ -1826,38 +1817,38 @@ public class ClusterDistributionManager implements DistributionManager {
culprits);
// Kill with no mercy
- if (this.serialThread != null) {
- this.serialThread.shutdownNow();
+ if (serialThread != null) {
+ serialThread.shutdownNow();
}
- if (this.viewThread != null) {
- this.viewThread.shutdownNow();
+ if (viewThread != null) {
+ viewThread.shutdownNow();
}
- if (this.functionExecutionThread != null) {
- this.functionExecutionThread.shutdownNow();
+ if (functionExecutionThread != null) {
+ functionExecutionThread.shutdownNow();
}
- if (this.functionExecutionPool != null) {
- this.functionExecutionPool.shutdownNow();
+ if (functionExecutionPool != null) {
+ functionExecutionPool.shutdownNow();
}
- if (this.partitionedRegionThread != null) {
- this.partitionedRegionThread.shutdownNow();
+ if (partitionedRegionThread != null) {
+ partitionedRegionThread.shutdownNow();
}
- if (this.partitionedRegionPool != null) {
- this.partitionedRegionPool.shutdownNow();
+ if (partitionedRegionPool != null) {
+ partitionedRegionPool.shutdownNow();
}
- if (this.highPriorityPool != null) {
- this.highPriorityPool.shutdownNow();
+ if (highPriorityPool != null) {
+ highPriorityPool.shutdownNow();
}
- if (this.waitingPool != null) {
- this.waitingPool.shutdownNow();
+ if (waitingPool != null) {
+ waitingPool.shutdownNow();
}
- if (this.prMetaDataCleanupThreadPool != null) {
- this.prMetaDataCleanupThreadPool.shutdownNow();
+ if (prMetaDataCleanupThreadPool != null) {
+ prMetaDataCleanupThreadPool.shutdownNow();
}
- if (this.threadPool != null) {
- this.threadPool.shutdownNow();
+ if (threadPool != null) {
+ threadPool.shutdownNow();
}
- Thread th = this.memberEventThread;
+ Thread th = memberEventThread;
if (th != null) {
clobberThread(th);
}
@@ -1873,7 +1864,7 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public boolean shutdownInProgress() {
- return this.shutdownInProgress;
+ return shutdownInProgress;
}
/**
@@ -1882,7 +1873,7 @@ public class ClusterDistributionManager implements DistributionManager {
*/
private void uncleanShutdown(boolean beforeJoined) {
try {
- this.closeInProgress = true; // set here also to fix bug 36736
+ closeInProgress = true; // set here also to fix bug 36736
removeAllHealthMonitors();
shutdownInProgress = true;
if (membershipManager != null) {
@@ -1904,8 +1895,8 @@ public class ClusterDistributionManager implements DistributionManager {
// ABSOLUTELY ESSENTIAL that we close the distribution channel!
try {
// For safety, but channel close in a finally AFTER this...
- if (this.stats != null) {
- this.stats.close();
+ if (stats != null) {
+ stats.close();
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
@@ -1913,10 +1904,10 @@ public class ClusterDistributionManager implements DistributionManager {
}
}
} finally {
- if (this.membershipManager != null) {
+ if (membershipManager != null) {
logger.info("Now closing distribution for {}",
- this.localAddress);
- this.membershipManager.disconnect(beforeJoined);
+ localAddress);
+ membershipManager.disconnect(beforeJoined);
}
}
}
@@ -1924,7 +1915,7 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public InternalDistributedSystem getSystem() {
- return this.system;
+ return system;
}
@Override
@@ -1936,42 +1927,42 @@ public class ClusterDistributionManager implements DistributionManager {
* Returns the transport configuration for this distribution manager
*/
RemoteTransportConfig getTransport() {
- return this.transport;
+ return transport;
}
@Override
public void addMembershipListener(MembershipListener l) {
- this.membershipListeners.putIfAbsent(l, Boolean.TRUE);
+ membershipListeners.putIfAbsent(l, Boolean.TRUE);
}
@Override
public void removeMembershipListener(MembershipListener l) {
- this.membershipListeners.remove(l);
+ membershipListeners.remove(l);
}
@Override
public Collection<MembershipListener> getMembershipListeners() {
- return Collections.unmodifiableSet(this.membershipListeners.keySet());
+ return Collections.unmodifiableSet(membershipListeners.keySet());
}
/**
* Adds a <code>MembershipListener</code> to this distribution manager.
*/
private void addAllMembershipListener(MembershipListener l) {
- synchronized (this.allMembershipListenersLock) {
+ synchronized (allMembershipListenersLock) {
Set<MembershipListener> newAllMembershipListeners =
- new HashSet<>(this.allMembershipListeners);
+ new HashSet<>(allMembershipListeners);
newAllMembershipListeners.add(l);
- this.allMembershipListeners = newAllMembershipListeners;
+ allMembershipListeners = newAllMembershipListeners;
}
}
@Override
public void removeAllMembershipListener(MembershipListener l) {
- synchronized (this.allMembershipListenersLock) {
+ synchronized (allMembershipListenersLock) {
Set<MembershipListener> newAllMembershipListeners =
- new HashSet<>(this.allMembershipListeners);
+ new HashSet<>(allMembershipListeners);
if (!newAllMembershipListeners.remove(l)) {
// There seems to be a race condition in which
// multiple departure events can be registered
@@ -1980,14 +1971,14 @@ public class ClusterDistributionManager implements DistributionManager {
// String s = "MembershipListener was never registered";
// throw new IllegalArgumentException(s);
}
- this.allMembershipListeners = newAllMembershipListeners;
+ allMembershipListeners = newAllMembershipListeners;
}
}
/**
* Returns true if this DM or the DistributedSystem owned by it is closing or is closed.
*/
- protected boolean isCloseInProgress() {
+ boolean isCloseInProgress() {
if (closeInProgress) {
return true;
}
@@ -2000,9 +1991,9 @@ public class ClusterDistributionManager implements DistributionManager {
}
private void handleViewInstalledEvent(ViewInstalledEvent ev) {
- synchronized (this.membershipViewIdGuard) {
- this.membershipViewIdAcknowledged = ev.getViewId();
- this.membershipViewIdGuard.notifyAll();
+ synchronized (membershipViewIdGuard) {
+ membershipViewIdAcknowledged = ev.getViewId();
+ membershipViewIdGuard.notifyAll();
}
}
@@ -2011,16 +2002,16 @@ public class ClusterDistributionManager implements DistributionManager {
* acknowledged by all membership listeners
*/
void waitForViewInstallation(long id) throws InterruptedException {
- if (id <= this.membershipViewIdAcknowledged) {
+ if (id <= membershipViewIdAcknowledged) {
return;
}
- synchronized (this.membershipViewIdGuard) {
- while (this.membershipViewIdAcknowledged < id && !this.stopper.isCancelInProgress()) {
+ synchronized (membershipViewIdGuard) {
+ while (membershipViewIdAcknowledged < id && !stopper.isCancelInProgress()) {
if (logger.isDebugEnabled()) {
logger.debug("waiting for view {}. Current DM view processed by all listeners is {}", id,
- this.membershipViewIdAcknowledged);
+ membershipViewIdAcknowledged);
}
- this.membershipViewIdGuard.wait();
+ membershipViewIdGuard.wait();
}
}
}
@@ -2051,13 +2042,13 @@ public class ClusterDistributionManager implements DistributionManager {
// if (getCancelCriterion().isCancelInProgress()) {
// break; // no message, just quit
// }
- if (!ClusterDistributionManager.this.system.isConnected
- && ClusterDistributionManager.this.isClosed()) {
+ if (!system.isConnected
+ && isClosed()) {
break;
}
try {
MemberEvent ev =
- ClusterDistributionManager.this.membershipEventQueue.take();
+ membershipEventQueue.take();
handleMemberEvent(ev);
} catch (InterruptedException e) {
if (isCloseInProgress()) {
@@ -2098,7 +2089,7 @@ public class ClusterDistributionManager implements DistributionManager {
stopper.checkCancelInProgress(null);
boolean interrupted = Thread.interrupted();
try {
- this.membershipEventQueue.put(ev);
+ membershipEventQueue.put(ev);
} catch (InterruptedException ex) {
interrupted = true;
stopper.checkCancelInProgress(ex);
@@ -2115,20 +2106,20 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public void close() {
if (!closed) {
- this.shutdown();
+ shutdown();
logger.info("Marking DistributionManager {} as closed.",
- this.localAddress);
- MembershipLogger.logShutdown(this.localAddress);
+ localAddress);
+ MembershipLogger.logShutdown(localAddress);
closed = true;
}
}
@Override
public void throwIfDistributionStopped() {
- if (this.shutdownMsgSent) {
+ if (shutdownMsgSent) {
throw new DistributedSystemDisconnectedException(
"Message distribution has terminated",
- this.getRootCause());
+ getRootCause());
}
}
@@ -2136,23 +2127,23 @@ public class ClusterDistributionManager implements DistributionManager {
* Returns true if this distribution manager has been closed.
*/
public boolean isClosed() {
- return this.closed;
+ return closed;
}
@Override
public void addAdminConsole(InternalDistributedMember theId) {
logger.info("New administration member detected at {}.", theId);
- synchronized (this.adminConsolesLock) {
- HashSet<InternalDistributedMember> tmp = new HashSet<>(this.adminConsoles);
+ synchronized (adminConsolesLock) {
+ HashSet<InternalDistributedMember> tmp = new HashSet<>(adminConsoles);
tmp.add(theId);
- this.adminConsoles = Collections.unmodifiableSet(tmp);
+ adminConsoles = Collections.unmodifiableSet(tmp);
}
}
@Override
public DMStats getStats() {
- return this.stats;
+ return stats;
}
@Override
@@ -2190,7 +2181,7 @@ public class ClusterDistributionManager implements DistributionManager {
MembershipManager mgr = membershipManager;
mgr.getViewLock().writeLock().lock();
try {
- synchronized (this.membersLock) {
+ synchronized (membersLock) {
// Don't let the members come and go while we are adding this
// listener. This ensures that the listener (probably a
// ReplyProcessor) gets a consistent view of the members.
@@ -2210,8 +2201,8 @@ public class ClusterDistributionManager implements DistributionManager {
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
- this.receivedStartupResponse = false;
- boolean ok = false;
+ receivedStartupResponse = false;
+ boolean ok;
// Be sure to add ourself to the equivalencies list!
Set<InetAddress> equivs = StartupMessage.getMyAddresses(this);
@@ -2265,11 +2256,11 @@ public class ClusterDistributionManager implements DistributionManager {
"One or more peers generated exceptions during connection attempt",
re);
}
- if (this.rejectionMessage != null) {
+ if (rejectionMessage != null) {
throw new IncompatibleSystemException(rejectionMessage);
}
- boolean receivedAny = this.receivedStartupResponse;
+ boolean receivedAny = receivedStartupResponse;
if (!ok) { // someone didn't reply
int unresponsiveCount;
@@ -2294,7 +2285,7 @@ public class ClusterDistributionManager implements DistributionManager {
// If there are other members, we must receive at least _one_ response
if (allOthers.size() != 0) { // there exist others
if (!receivedAny) { // and none responded
- StringBuffer sb = new StringBuffer();
+ StringBuilder sb = new StringBuilder();
Iterator itt = allOthers.iterator();
while (itt.hasNext()) {
Object m = itt.next();
@@ -2308,8 +2299,7 @@ public class ClusterDistributionManager implements DistributionManager {
throw new SystemConnectException(
String.format(
"Received no connection acknowledgments from any of the %s senior cache members: %s",
-
- new Object[] {Integer.toString(allOthers.size()), sb.toString()}));
+ Integer.toString(allOthers.size()), sb.toString()));
} // and none responded
} // there exist others
@@ -2355,7 +2345,7 @@ public class ClusterDistributionManager implements DistributionManager {
// OK, I don't _quite_ trust the list to be current, so let's
// prune it here.
Iterator it = unfinishedStartups.iterator();
- synchronized (this.membersLock) {
+ synchronized (membersLock) {
while (it.hasNext()) {
InternalDistributedMember m = (InternalDistributedMember) it.next();
if (!isCurrentMember(m)) {
@@ -2376,7 +2366,7 @@ public class ClusterDistributionManager implements DistributionManager {
return; // not yet done with startup
if (!unfinishedStartups.remove(m))
return;
- String msg = null;
+ String msg;
if (departed) {
msg =
"Stopped waiting for startup reply from <{}> because the peer departed the view.";
@@ -2388,7 +2378,7 @@ public class ClusterDistributionManager implements DistributionManager {
int numLeft = unfinishedStartups.size();
if (numLeft != 0) {
logger.info("Still awaiting {} response(s) from: {}.",
- new Object[] {Integer.valueOf(numLeft), unfinishedStartups});
+ new Object[] {numLeft, unfinishedStartups});
}
} // synchronized
}
@@ -2401,26 +2391,17 @@ public class ClusterDistributionManager implements DistributionManager {
void processStartupResponse(InternalDistributedMember sender, String theRejectionMessage) {
removeUnfinishedStartup(sender, false);
synchronized (this) {
- if (!this.receivedStartupResponse) {
+ if (!receivedStartupResponse) {
// only set the cacheTimeDelta once
- this.receivedStartupResponse = true;
+ receivedStartupResponse = true;
}
- if (theRejectionMessage != null && this.rejectionMessage == null) {
+ if (theRejectionMessage != null && rejectionMessage == null) {
// remember the first non-null rejection. This fixes bug 33266
- this.rejectionMessage = theRejectionMessage;
+ rejectionMessage = theRejectionMessage;
}
}
}
- /**
- * Based on a recent JGroups view, return a member that might be the next elder.
- *
- * @return the elder candidate, possibly this VM.
- */
- private InternalDistributedMember getElderCandidate() {
- return clusterElderManager.getElderCandidate();
- }
-
private String prettifyReason(String r) {
final String str = "java.io.IOException:";
if (r.startsWith(str)) {
@@ -2442,12 +2423,12 @@ public class ClusterDistributionManager implements DistributionManager {
if (isCurrentMember(theId)) {
// Destroy underlying member's resources
reason = prettifyReason(reason);
- synchronized (this.membersLock) {
+ synchronized (membersLock) {
if (logger.isDebugEnabled()) {
logger.debug("DistributionManager: removing member <{}>; crashed {}; reason = {}", theId,
crashed, reason);
}
- Map<InternalDistributedMember, InternalDistributedMember> tmp = new HashMap<>(this.members);
+ Map<InternalDistributedMember, InternalDistributedMember> tmp = new HashMap<>(members);
if (tmp.remove(theId) != null) {
// Note we don't modify in place. This allows reader to get snapshots
// without locking.
@@ -2456,7 +2437,7 @@ public class ClusterDistributionManager implements DistributionManager {
} else {
tmp = Collections.unmodifiableMap(tmp);
}
- this.members = tmp;
+ members = tmp;
result = true;
} else {
@@ -2465,16 +2446,16 @@ public class ClusterDistributionManager implements DistributionManager {
// an explicit remove followed by an implicit one caused
// by a JavaGroup view change
}
- Set<InternalDistributedMember> tmp2 = new HashSet<>(this.membersAndAdmin);
+ Set<InternalDistributedMember> tmp2 = new HashSet<>(membersAndAdmin);
if (tmp2.remove(theId)) {
if (tmp2.isEmpty()) {
tmp2 = Collections.emptySet();
} else {
tmp2 = Collections.unmodifiableSet(tmp2);
}
- this.membersAndAdmin = tmp2;
+ membersAndAdmin = tmp2;
}
- this.removeHostedLocators(theId);
+ removeHostedLocators(theId);
} // synchronized
} // if
@@ -2491,8 +2472,8 @@ public class ClusterDistributionManager implements DistributionManager {
*
*/
private void handleManagerStartup(InternalDistributedMember theId) {
- HashMap<InternalDistributedMember, InternalDistributedMember> tmp = null;
- synchronized (this.membersLock) {
+ HashMap<InternalDistributedMember, InternalDistributedMember> tmp;
+ synchronized (membersLock) {
// Note test is under membersLock
if (members.containsKey(theId)) {
return; // already accounted for
@@ -2500,17 +2481,17 @@ public class ClusterDistributionManager implements DistributionManager {
// Note we don't modify in place. This allows reader to get snapshots
// without locking.
- tmp = new HashMap<>(this.members);
+ tmp = new HashMap<>(members);
tmp.put(theId, theId);
- this.members = Collections.unmodifiableMap(tmp);
+ members = Collections.unmodifiableMap(tmp);
- Set<InternalDistributedMember> stmp = new HashSet<>(this.membersAndAdmin);
+ Set<InternalDistributedMember> stmp = new HashSet<>(membersAndAdmin);
stmp.add(theId);
- this.membersAndAdmin = Collections.unmodifiableSet(stmp);
+ membersAndAdmin = Collections.unmodifiableSet(stmp);
} // synchronized
if (theId.getVmKind() != ClusterDistributionManager.LOCATOR_DM_TYPE) {
- this.stats.incNodes(1);
+ stats.incNodes(1);
}
logger.info("Admitting member <{}>. Now there are {} non-admin member(s).",
theId, tmp.size());
@@ -2520,10 +2501,10 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public boolean isCurrentMember(DistributedMember id) {
Set m;
- synchronized (this.membersLock) {
+ synchronized (membersLock) {
// access to members synchronized under membersLock in order to
// ensure serialization
- m = this.membersAndAdmin;
+ m = membersAndAdmin;
}
return m.contains(id);
}
@@ -2534,17 +2515,17 @@ public class ClusterDistributionManager implements DistributionManager {
*/
private void handleConsoleStartup(InternalDistributedMember theId) {
// if we have an all listener then notify it NOW.
- HashSet<InternalDistributedMember> tmp = null;
- synchronized (this.membersLock) {
+ HashSet<InternalDistributedMember> tmp;
+ synchronized (membersLock) {
// Note test is under membersLock
if (membersAndAdmin.contains(theId))
return; // already accounted for
// Note we don't modify in place. This allows reader to get snapshots
// without locking.
- tmp = new HashSet<>(this.membersAndAdmin);
+ tmp = new HashSet<>(membersAndAdmin);
tmp.add(theId);
- this.membersAndAdmin = Collections.unmodifiableSet(tmp);
+ membersAndAdmin = Collections.unmodifiableSet(tmp);
} // synchronized
for (MembershipListener listener : allMembershipListeners) {
@@ -2583,16 +2564,16 @@ public class ClusterDistributionManager implements DistributionManager {
String reason) {
boolean removedConsole = false;
boolean removedMember = false;
- synchronized (this.membersLock) {
+ synchronized (membersLock) {
// to fix bug 39747 we can only remove this member from
// membersAndAdmin if it is not in members.
// This happens when we have an admin member colocated with a normal DS.
// In this case we need for the normal DS to shutdown or crash.
- if (!this.members.containsKey(theId)) {
+ if (!members.containsKey(theId)) {
if (logger.isDebugEnabled())
logger.debug("DistributionManager: removing admin member <{}>; crashed = {}; reason = {}",
theId, crashed, reason);
- Set<InternalDistributedMember> tmp = new HashSet<>(this.membersAndAdmin);
+ Set<InternalDistributedMember> tmp = new HashSet<>(membersAndAdmin);
if (tmp.remove(theId)) {
// Note we don't modify in place. This allows reader to get snapshots
// without locking.
@@ -2601,7 +2582,7 @@ public class ClusterDistributionManager implements DistributionManager {
} else {
tmp = Collections.unmodifiableSet(tmp);
}
- this.membersAndAdmin = tmp;
+ membersAndAdmin = tmp;
removedMember = true;
} else {
// Don't get upset since this can happen twice due to
@@ -2611,17 +2592,17 @@ public class ClusterDistributionManager implements DistributionManager {
}
removeHostedLocators(theId);
}
- synchronized (this.adminConsolesLock) {
- if (this.adminConsoles.contains(theId)) {
+ synchronized (adminConsolesLock) {
+ if (adminConsoles.contains(theId)) {
removedConsole = true;
- Set<InternalDistributedMember> tmp = new HashSet<>(this.adminConsoles);
+ Set<InternalDistributedMember> tmp = new HashSet<>(adminConsoles);
tmp.remove(theId);
if (tmp.isEmpty()) {
tmp = Collections.emptySet();
} else {
tmp = Collections.unmodifiableSet(tmp);
}
- this.adminConsoles = tmp;
+ adminConsoles = tmp;
}
}
if (removedMember) {
@@ -2630,7 +2611,7 @@ public class ClusterDistributionManager implements DistributionManager {
}
}
if (removedConsole) {
- String msg = null;
+ String msg;
if (crashed) {
msg = "Administration member at {} crashed: {}";
} else {
@@ -2643,7 +2624,7 @@ public class ClusterDistributionManager implements DistributionManager {
}
void shutdownMessageReceived(InternalDistributedMember theId, String reason) {
- this.membershipManager.shutdownMessageReceived(theId, reason);
+ membershipManager.shutdownMessageReceived(theId, reason);
handleManagerDeparture(theId, false,
"shutdown message received");
}
@@ -2669,7 +2650,7 @@ public class ClusterDistributionManager implements DistributionManager {
if (removeManager(theId, p_crashed, p_reason)) {
if (theId.getVmKind() != ClusterDistributionManager.LOCATOR_DM_TYPE) {
- this.stats.incNodes(-1);
+ stats.incNodes(-1);
}
String msg;
if (p_crashed && !isCloseInProgress()) {
@@ -2684,7 +2665,7 @@ public class ClusterDistributionManager implements DistributionManager {
logger.info(msg, new Object[] {theId, prettifyReason(p_reason)});
// Remove this manager from the serialQueueExecutor.
- if (this.serialQueuedExecutorPool != null) {
+ if (serialQueuedExecutorPool != null) {
serialQueuedExecutorPool.handleMemberDeparture(theId);
}
}
@@ -2726,7 +2707,7 @@ public class ClusterDistributionManager implements DistributionManager {
}
ShutdownMessage m = new ShutdownMessage();
- InternalDistributedMember theId = this.getDistributionManagerId();
+ InternalDistributedMember theId = getDistributionManagerId();
m.setDistributionManagerId(theId);
Set<InternalDistributedMember> allOthers = new HashSet<>(getViewMembers());
allOthers.remove(getDistributionManagerId());
@@ -2734,7 +2715,7 @@ public class ClusterDistributionManager implements DistributionManager {
// Address recipient = (Address) m.getRecipient();
if (logger.isTraceEnabled()) {
- logger.trace("{} Sending {} to {}", this.getDistributionManagerId(), m,
+ logger.trace("{} Sending {} to {}", getDistributionManagerId(), m,
m.getRecipientsDescription());
}
@@ -2742,7 +2723,7 @@ public class ClusterDistributionManager implements DistributionManager {
// m.resetTimestamp(); // nanotimers across systems don't match
long startTime = DistributionStats.getStatTime();
sendViaMembershipManager(m.getRecipients(), m, this, stats);
- this.stats.incSentMessages(1L);
+ stats.incSentMessages(1L);
if (DistributionStats.enableClockStats) {
stats.incSentMessagesTime(DistributionStats.getStatTime() - startTime);
}
@@ -2753,7 +2734,7 @@ public class ClusterDistributionManager implements DistributionManager {
} finally {
// Even if the message wasn't sent, *lie* about it, so that
// everyone believes that message distribution is done.
- this.shutdownMsgSent = true;
+ shutdownMsgSent = true;
}
}
@@ -2767,7 +2748,7 @@ public class ClusterDistributionManager implements DistributionManager {
case SERIAL_EXECUTOR:
return getSerialExecutor(sender);
case VIEW_EXECUTOR:
- return this.viewThread;
+ return viewThread;
case HIGH_PRIORITY_EXECUTOR:
return getHighPriorityThreadPool();
case WAITING_POOL_EXECUTOR:
@@ -2795,8 +2776,7 @@ public class ClusterDistributionManager implements DistributionManager {
long startTime = DistributionStats.getStatTime();
Set<InternalDistributedMember> result =
- sendViaMembershipManager(message.getRecipients(), message,
- ClusterDistributionManager.this, this.stats);
+ sendViaMembershipManager(message.getRecipients(), message, this, stats);
long endTime = 0L;
if (DistributionStats.enableClockStats) {
endTime = NanoTimer.getTime();
@@ -2826,7 +2806,6 @@ public class ClusterDistributionManager implements DistributionManager {
*/
private Set<InternalDistributedMember> sendMessage(DistributionMessage message)
throws NotSerializableException {
- Set<InternalDistributedMember> result = null;
try {
// Verify we're not too far into the shutdown
stopper.checkCancelInProgress(null);
@@ -2834,28 +2813,23 @@ public class ClusterDistributionManager implements DistributionManager {
// avoid race condition during startup
waitUntilReadyToSendMsgs(message);
- result = sendOutgoing(message);
+ return sendOutgoing(message);
} catch (NotSerializableException | ToDataException | ReenteredConnectException
| InvalidDeltaException | CancelException ex) {
throw ex;
} catch (Exception ex) {
- ClusterDistributionManager.this.exceptionInThreads = true;
+ exceptionInThreads = true;
String receiver = "NULL";
if (message != null) {
receiver = message.getRecipientsDescription();
}
- logger.fatal(String.format("While pushing message <%s> to %s",
- new Object[] {message, receiver}),
- ex);
- if (message == null || message.forAll())
+ logger.fatal(String.format("While pushing message <%s> to %s", message, receiver), ex);
+ if (message == null || message.forAll()) {
return null;
- result = new HashSet<>();
- for (int i = 0; i < message.getRecipients().length; i++)
- result.add(message.getRecipients()[i]);
- return result;
+ }
+ return new HashSet<>(Arrays.asList(message.getRecipients()));
}
- return result;
}
/**
@@ -2888,12 +2862,7 @@ public class ClusterDistributionManager implements DistributionManager {
* will only be initialized upto the point at which it called startThreads
*/
waitUntilReadyForMessages();
- message.schedule(ClusterDistributionManager.this);
- }
-
- private List<InternalDistributedMember> getElderCandidates() {
-
- return clusterElderManager.getElderCandidates();
+ message.schedule(this);
}
@Override
@@ -2928,63 +2897,62 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public ExecutorService getThreadPool() {
- return this.threadPool;
+ return threadPool;
}
@Override
public ExecutorService getHighPriorityThreadPool() {
- return this.highPriorityPool;
+ return highPriorityPool;
}
@Override
public ExecutorService getWaitingThreadPool() {
- return this.waitingPool;
+ return waitingPool;
}
@Override
public ExecutorService getPrMetaDataCleanupThreadPool() {
- return this.prMetaDataCleanupThreadPool;
+ return prMetaDataCleanupThreadPool;
}
private Executor getPartitionedRegionExcecutor() {
- if (this.partitionedRegionThread != null) {
- return this.partitionedRegionThread;
+ if (partitionedRegionThread != null) {
+ return partitionedRegionThread;
} else {
- return this.partitionedRegionPool;
+ return partitionedRegionPool;
}
}
@Override
public Executor getFunctionExecutor() {
- if (this.functionExecutionThread != null) {
- return this.functionExecutionThread;
+ if (functionExecutionThread != null) {
+ return functionExecutionThread;
} else {
- return this.functionExecutionPool;
+ return functionExecutionPool;
}
}
private Executor getSerialExecutor(InternalDistributedMember sender) {
if (MULTI_SERIAL_EXECUTORS) {
- return this.serialQueuedExecutorPool.getThrottledSerialExecutor(sender);
+ return serialQueuedExecutorPool.getThrottledSerialExecutor(sender);
} else {
- return this.serialThread;
+ return serialThread;
}
}
/** returns the serialThread's queue if throttling is being used, null if not */
public OverflowQueueWithDMStats<Runnable> getSerialQueue(InternalDistributedMember sender) {
if (MULTI_SERIAL_EXECUTORS) {
- return this.serialQueuedExecutorPool.getSerialQueue(sender);
+ return serialQueuedExecutorPool.getSerialQueue(sender);
} else {
- return this.serialQueue;
+ return serialQueue;
}
}
@Override
- /** returns the Threads Monitoring instance */
public ThreadsMonitoring getThreadMonitoring() {
- return this.threadMonitor;
+ return threadMonitor;
}
/**
@@ -3012,7 +2980,7 @@ public class ClusterDistributionManager implements DistributionManager {
* Returns the agent that owns this distribution manager. (in ConsoleDistributionManager)
*/
public RemoteGfManagerAgent getAgent() {
- return this.agent;
+ return agent;
}
/**
@@ -3023,11 +2991,11 @@ public class ClusterDistributionManager implements DistributionManager {
* distribution manager
*/
public String getDistributionConfigDescription() {
- if (this.agent == null) {
+ if (agent == null) {
return null;
} else {
- return this.agent.getTransport().toString();
+ return agent.getTransport().toString();
}
}
@@ -3047,7 +3015,7 @@ public class ClusterDistributionManager implements DistributionManager {
*/
@Override
public HealthMonitor getHealthMonitor(InternalDistributedMember owner) {
- return this.hmMap.get(owner);
+ return hmMap.get(owner);
}
/**
@@ -3066,13 +3034,13 @@ public class ClusterDistributionManager implements DistributionManager {
final HealthMonitor hm = getHealthMonitor(owner);
if (hm != null) {
hm.stop();
- this.hmMap.remove(owner);
+ hmMap.remove(owner);
}
}
{
HealthMonitorImpl newHm = new HealthMonitorImpl(owner, cfg, this);
newHm.start();
- this.hmMap.put(owner, newHm);
+ hmMap.put(owner, newHm);
}
}
@@ -3086,12 +3054,12 @@ public class ClusterDistributionManager implements DistributionManager {
final HealthMonitor hm = getHealthMonitor(owner);
if (hm != null && hm.getId() == theId) {
hm.stop();
- this.hmMap.remove(owner);
+ hmMap.remove(owner);
}
}
private void removeAllHealthMonitors() {
- Iterator it = this.hmMap.values().iterator();
+ Iterator it = hmMap.values().iterator();
while (it.hasNext()) {
HealthMonitor hm = (HealthMonitor) it.next();
hm.stop();
@@ -3101,7 +3069,7 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public Set<InternalDistributedMember> getAdminMemberSet() {
- return this.adminConsoles;
+ return adminConsoles;
}
/** Returns count of members filling the specified role */
@@ -3199,7 +3167,7 @@ public class ClusterDistributionManager implements DistributionManager {
boolean throttlingDisabled, ThreadsMonitoring tMonitoring) {
this.stats = stats;
this.throttlingDisabled = throttlingDisabled;
- this.threadMonitoring = tMonitoring;
+ threadMonitoring = tMonitoring;
}
/*
@@ -3227,7 +3195,7 @@ public class ClusterDistributionManager implements DistributionManager {
}
// If Map is full, use the threads in round-robin fashion.
if (queueId == null) {
- queueId = Integer.valueOf((serialQueuedExecutorMap.size() + 1) % MAX_SERIAL_QUEUE_THREAD);
+ queueId = (serialQueuedExecutorMap.size() + 1) % MAX_SERIAL_QUEUE_THREAD;
}
senderToSerialQueueIdMap.put(sender, queueId);
}
@@ -3282,7 +3250,7 @@ public class ClusterDistributionManager implements DistributionManager {
Thread.currentThread().interrupt();
}
}
- this.stats.getSerialQueueHelper().incThrottleCount();
+ stats.getSerialQueueHelper().incThrottleCount();
} while (stats.getSerialQueueBytes() >= TOTAL_SERIAL_QUEUE_BYTE_LIMIT);
}
return executor;
@@ -3292,7 +3260,7 @@ public class ClusterDistributionManager implements DistributionManager {
* Returns the serial queue executor for the given sender.
*/
ExecutorService getSerialExecutor(InternalDistributedMember sender) {
- ExecutorService executor = null;
+ ExecutorService executor;
Integer queueId = getQueueId(sender, true);
if ((executor =
serialQueuedExecutorMap.get(queueId)) != null) {
@@ -3319,19 +3287,19 @@ public class ClusterDistributionManager implements DistributionManager {
OverflowQueueWithDMStats<Runnable> poolQueue;
- if (SERIAL_QUEUE_BYTE_LIMIT == 0 || this.throttlingDisabled) {
+ if (SERIAL_QUEUE_BYTE_LIMIT == 0 || throttlingDisabled) {
poolQueue = new OverflowQueueWithDMStats<>(stats.getSerialQueueHelper());
} else {
poolQueue = new ThrottlingMemLinkedQueueWithDMStats<>(SERIAL_QUEUE_BYTE_LIMIT,
SERIAL_QUEUE_THROTTLE, SERIAL_QUEUE_SIZE_LIMIT, SERIAL_QUEUE_SIZE_THROTTLE,
- this.stats.getSerialQueueHelper());
+ stats.getSerialQueueHelper());
}
serialQueuedMap.put(id, poolQueue);
return LoggingExecutors.newSerialThreadPool("Pooled Serial Message Processor" + id + "-",
thread -> stats.incSerialPooledThreadStarts(), this::doSerialPooledThread,
- this.stats.getSerialPooledProcessorHelper(), threadMonitoring, poolQueue);
+ stats.getSerialPooledProcessorHelper(), threadMonitoring, poolQueue);
}
private void doSerialPooledThread(Runnable command) {
@@ -3360,8 +3328,7 @@ public class ClusterDistributionManager implements DistributionManager {
senderToSerialQueueIdMap.remove(member);
// Check if any other members are using the same executor.
- for (Iterator iter = senderToSerialQueueIdMap.values().iterator(); iter.hasNext();) {
- Integer value = (Integer) iter.next();
+ for (Integer value : senderToSerialQueueIdMap.values()) {
if (value.equals(queueId)) {
isUsed = true;
break;
@@ -3381,12 +3348,11 @@ public class ClusterDistributionManager implements DistributionManager {
}
private void awaitTermination(long time, TimeUnit unit) throws InterruptedException {
- long timeNanos = unit.toNanos(time);
- long remainingNanos = timeNanos;
+ long remainingNanos = unit.toNanos(time);
long start = System.nanoTime();
for (ExecutorService executor : serialQueuedExecutorMap.values()) {
executor.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
- remainingNanos = timeNanos = (System.nanoTime() - start);
+ remainingNanos = (System.nanoTime() - start);
if (remainingNanos <= 0) {
return;
}
@@ -3408,7 +3374,7 @@ public class ClusterDistributionManager implements DistributionManager {
private class DMListener implements DistributedMembershipListener {
ClusterDistributionManager dm;
- public DMListener(ClusterDistributionManager dm) {
+ DMListener(ClusterDistributionManager dm) {
this.dm = dm;
}
@@ -3420,7 +3386,7 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public void membershipFailure(String reason, Throwable t) {
exceptionInThreads = true;
- ClusterDistributionManager.this.rootCause = t;
+ rootCause = t;
getSystem().disconnect(reason, t, true);
}
@@ -3493,7 +3459,7 @@ public class ClusterDistributionManager implements DistributionManager {
}
public InternalDistributedMember getId() {
- return this.id;
+ return id;
}
void handleEvent(ClusterDistributionManager manager) {
@@ -3623,16 +3589,16 @@ public class ClusterDistributionManager implements DistributionManager {
}
public InternalDistributedMember whoSuspected() {
- return this.whoSuspected;
+ return whoSuspected;
}
public String getReason() {
- return this.reason;
+ return reason;
}
@Override
public String toString() {
- return "member " + getId() + " suspected by: " + this.whoSuspected + " reason: " + reason;
+ return "member " + getId() + " suspected by: " + whoSuspected + " reason: " + reason;
}
@Override
@@ -3655,7 +3621,7 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public String toString() {
- return "view installed: " + this.view;
+ return "view installed: " + view;
}
@Override
@@ -3681,11 +3647,11 @@ public class ClusterDistributionManager implements DistributionManager {
}
public Set<InternalDistributedMember> getFailures() {
- return this.failures;
+ return failures;
}
public List<InternalDistributedMember> getRemaining() {
- return this.remaining;
+ return remaining;
}
@Override
@@ -3707,7 +3673,7 @@ public class ClusterDistributionManager implements DistributionManager {
*/
@Override
public Throwable getRootCause() {
- return this.rootCause;
+ return rootCause;
}
/*
@@ -3717,7 +3683,7 @@ public class ClusterDistributionManager implements DistributionManager {
*/
@Override
public void setRootCause(Throwable t) {
- this.rootCause = t;
+ rootCause = t;
}
/*
@@ -3748,9 +3714,8 @@ public class ClusterDistributionManager implements DistributionManager {
} else {
buddyMembers.add(targetMember);
Set<InetAddress> targetAddrs = getEquivalents(targetMember.getInetAddress());
- for (Iterator i = getDistributionManagerIds().iterator(); i.hasNext();) {
- InternalDistributedMember o = (InternalDistributedMember) i.next();
- if (SetUtils.intersectsWith(targetAddrs, getEquivalents(o.getInetAddress()))) {
+ for (InternalDistributedMember o : getDistributionManagerIds()) {
+ if (!Collections.disjoint(targetAddrs, getEquivalents(o.getInetAddress()))) {
buddyMembers.add(o);
}
}
@@ -3773,14 +3738,14 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public void acquireGIIPermitUninterruptibly() {
- this.parallelGIIs.acquireUninterruptibly();
- this.stats.incInitialImageRequestsInProgress(1);
+ parallelGIIs.acquireUninterruptibly();
+ stats.incInitialImageRequestsInProgress(1);
}
@Override
public void releaseGIIPermit() {
- this.stats.incInitialImageRequestsInProgress(-1);
- this.parallelGIIs.release();
+ stats.incInitialImageRequestsInProgress(-1);
+ parallelGIIs.release();
}
public void setDistributedSystemId(int distributedSystemId) {
@@ -3791,7 +3756,7 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public int getDistributedSystemId() {
- return this.distributedSystemId;
+ return distributedSystemId;
}
/**
@@ -3808,10 +3773,9 @@ public class ClusterDistributionManager implements DistributionManager {
requiresMessage.addAll(ids);
ids.remove(localAddress);
} else {
- for (Iterator it = ids.iterator(); it.hasNext();) {
- InternalDistributedMember mbr = (InternalDistributedMember) it.next();
+ for (InternalDistributedMember mbr : ids) {
if (mbr.getProcessId() > 0
- && mbr.getInetAddress().equals(this.localAddress.getInetAddress())) {
+ && mbr.getInetAddress().equals(localAddress.getInetAddress())) {
if (!mbr.equals(localAddress)) {
if (!OSProcess.printStacks(mbr.getProcessId(), false)) {
requiresMessage.add(mbr);
@@ -3850,9 +3814,9 @@ public class ClusterDistributionManager implements DistributionManager {
public Set<InternalDistributedMember> getNormalDistributionManagerIds() {
// access to members synchronized under membersLock in order to
// ensure serialization
- synchronized (this.membersLock) {
+ synchronized (membersLock) {
HashSet<InternalDistributedMember> result = new HashSet<>();
- for (InternalDistributedMember m : this.members.keySet()) {
+ for (InternalDistributedMember m : members.keySet()) {
if (m.getVmKind() != ClusterDistributionManager.LOCATOR_DM_TYPE) {
result.add(m);
}
@@ -3865,9 +3829,9 @@ public class ClusterDistributionManager implements DistributionManager {
public Set<InternalDistributedMember> getLocatorDistributionManagerIds() {
// access to members synchronized under membersLock in order to
// ensure serialization
- synchronized (this.membersLock) {
+ synchronized (membersLock) {
HashSet<InternalDistributedMember> result = new HashSet<>();
- for (InternalDistributedMember m : this.members.keySet()) {
+ for (InternalDistributedMember m : members.keySet()) {
if (m.getVmKind() == ClusterDistributionManager.LOCATOR_DM_TYPE) {
result.add(m);
}
@@ -3878,17 +3842,17 @@ public class ClusterDistributionManager implements DistributionManager {
@Override
public void setCache(InternalCache instance) {
- this.cache = instance;
+ cache = instance;
}
@Override
public InternalCache getCache() {
- return this.cache;
+ return cache;
}
@Override
public InternalCache getExistingCache() {
- InternalCache result = this.cache;
+ InternalCache result = cache;
if (result == null) {
throw new CacheClosedException(
"A cache has not yet been created.");
diff --git a/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionAdvisor.java b/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionAdvisor.java
index e55327b..669f59a 100644
--- a/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionAdvisor.java
+++ b/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionAdvisor.java
@@ -190,11 +190,11 @@ public class DistributionAdvisor {
/**
* The membership listener registered with the dm.
*/
- private final MembershipListener ml;
+ private final MembershipListener membershipListener;
protected DistributionAdvisor(DistributionAdvisee advisee) {
this.advisee = advisee;
- this.ml = new MembershipListener() {
+ membershipListener = new MembershipListener() {
@Override
public void memberJoined(DistributionManager distributionManager,
@@ -237,7 +237,7 @@ public class DistributionAdvisor {
protected void initialize() {
subInit();
- getDistributionManager().addMembershipListener(this.ml);
+ getDistributionManager().addMembershipListener(membershipListener);
}
private void subInit() {
@@ -250,8 +250,8 @@ public class DistributionAdvisor {
* @return true if a delta-gii should be performed
*/
public boolean shouldSyncForCrashedMember(InternalDistributedMember id) {
- return (this.advisee instanceof DistributedRegion)
- && ((DistributedRegion) this.advisee).shouldSyncForCrashedMember(id);
+ return (advisee instanceof DistributedRegion)
+ && ((DistributedRegion) advisee).shouldSyncForCrashedMember(id);
}
/** perform a delta-GII for the given lost member */
@@ -318,8 +318,8 @@ public class DistributionAdvisor {
/** find the region for a delta-gii operation (synch) */
public DistributedRegion getRegionForDeltaGII() {
- if (this.advisee instanceof DistributedRegion) {
- return (DistributedRegion) this.advisee;
+ if (advisee instanceof DistributedRegion) {
+ return (DistributedRegion) advisee;
}
return null;
}
@@ -327,7 +327,7 @@ public class DistributionAdvisor {
protected String toStringWithProfiles() {
final StringBuilder sb = new StringBuilder(toString());
sb.append(" with profiles=(");
- Profile[] profs = this.profiles; // volatile read
+ Profile[] profs = profiles; // volatile read
for (int i = 0; i < profs.length; i++) {
if (i > 0) {
sb.append(", ");
@@ -345,7 +345,7 @@ public class DistributionAdvisor {
*/
protected int incrementAndGetVersion() {
// NOTE: int should rollover if value is Integer.MAX_VALUE
- return this.profileVersionSequencer.incrementAndGet();
+ return profileVersionSequencer.incrementAndGet();
}
/**
@@ -379,7 +379,7 @@ public class DistributionAdvisor {
}
public DistributionAdvisee getAdvisee() {
- return this.advisee;
+ return advisee;
}
/**
@@ -390,10 +390,10 @@ public class DistributionAdvisor {
public void close() {
try {
synchronized (this) {
- this.membershipClosed = true;
+ membershipClosed = true;
operationMonitor.close();
}
- getDistributionManager().removeMembershipListener(this.ml);
+ getDistributionManager().removeMembershipListener(membershipListener);
} catch (CancelException e) {
// if distribution has stopped, above is a no-op.
} catch (IllegalArgumentException ignore) {
@@ -407,7 +407,8 @@ public class DistributionAdvisor {
* profile is removed, and return adviseGeneric(). This ensures that no membership listener calls
* are missed, but there is no guarantee that there won't be redundant listener calls.
*/
- public Set addMembershipListenerAndAdviseGeneric(MembershipListener listener) {
+ public Set<InternalDistributedMember> addMembershipListenerAndAdviseGeneric(
+ MembershipListener listener) {
initializationGate(); // exchange profiles before acquiring lock on membershipListeners
membershipListeners.putIfAbsent(listener, Boolean.TRUE);
return adviseGeneric();
@@ -442,18 +443,18 @@ public class DistributionAdvisor {
/** Called by CreateRegionProcessor after it does its own profile exchange */
public void setInitialized() {
- synchronized (this.initializeLock) {
- this.initialized = true;
+ synchronized (initializeLock) {
+ initialized = true;
}
}
/** Return true if exchanged profiles */
public boolean initializationGate() {
- if (this.initialized) {
+ if (initialized) {
return false;
}
- synchronized (this.initializeLock) {
- if (!this.initialized) {
+ synchronized (initializeLock) {
+ if (!initialized) {
exchangeProfiles();
return true;
}
@@ -463,8 +464,8 @@ public class DistributionAdvisor {
// wait for pending profile exchange to complete before returning
public boolean isInitialized() {
- synchronized (this.initializeLock) {
- return this.initialized;
+ synchronized (initializeLock) {
+ return initialized;
}
}
@@ -475,7 +476,7 @@ public class DistributionAdvisor {
* @since GemFire 5.7
*/
protected boolean pollIsInitialized() {
- return this.initialized;
+ return initialized;
}
/**
@@ -485,7 +486,7 @@ public class DistributionAdvisor {
*/
public void dumpProfiles(String infoMsg) {
- Profile[] profs = this.profiles;
+ Profile[] profs = profiles;
final StringBuilder buf = new StringBuilder(2000);
if (infoMsg != null) {
buf.append(infoMsg);
@@ -756,7 +757,7 @@ public class DistributionAdvisor {
protected boolean stillInView(ProfileId id) {
if (id instanceof InternalDistributedMember) {
InternalDistributedMember memberId = (InternalDistributedMember) id;
- return this.getDistributionManager().getViewMembers().contains(memberId);
+ return getDistributionManager().getViewMembers().contains(memberId);
} else {
// if id is not a InternalDistributedMember then return false
return false;
@@ -852,7 +853,7 @@ public class DistributionAdvisor {
logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "removeId: tracking removal of {}",
profileToRemove);
}
- this.removedProfiles.put(profileToRemove.getDistributedMember(),
+ removedProfiles.put(profileToRemove.getDistributedMember(),
profileToRemove.getSerialNumber());
basicRemoveId(profileToRemove.getId(), crashed, destroyed);
profileToRemove = getProfile(memberId);
@@ -860,7 +861,7 @@ public class DistributionAdvisor {
return result;
} else {
// Garbage collect; this profile is no longer pertinent
- this.removedProfiles.remove(memberId);
+ removedProfiles.remove(memberId);
boolean result = basicRemoveId(memberId, crashed, destroyed);
while (basicRemoveId(memberId, crashed, destroyed)) {
// keep removing profiles that match until we have no more
@@ -964,7 +965,7 @@ public class DistributionAdvisor {
logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE,
"updateRemovedProfiles: garbage collecting member {}", memberId);
}
- this.removedProfiles.remove(memberId);
+ removedProfiles.remove(memberId);
// Always make sure that this member is removed from the advisor
removedId = basicRemoveId(memberId, false, regionDestroyed);
@@ -990,18 +991,18 @@ public class DistributionAdvisor {
public synchronized int getNumProfiles() {
- return this.numActiveProfiles;
+ return numActiveProfiles;
}
/**
* Caller must be synchronized on this. Overridden in BucketAdvisor.
*/
private void setNumActiveProfiles(int newValue) {
- this.numActiveProfiles = newValue;
+ numActiveProfiles = newValue;
}
public Profile getProfile(ProfileId id) {
- Profile[] allProfiles = this.profiles; // volatile read
+ Profile[] allProfiles = profiles; // volatile read
boolean isIDM = (id instanceof InternalDistributedMember);
for (Profile allProfile : allProfiles) {
if (isIDM) {
@@ -1020,7 +1021,7 @@ public class DistributionAdvisor {
/** exchange profiles to initialize this advisor */
public void exchangeProfiles() {
Assert.assertHoldsLock(this, false); // causes deadlock
- Assert.assertHoldsLock(this.initializeLock, true);
+ Assert.assertHoldsLock(initializeLock, true);
new UpdateAttributesProcessor(getAdvisee()).distribute(true);
setInitialized();
}
@@ -1162,7 +1163,7 @@ public class DistributionAdvisor {
protected Set<InternalDistributedMember> adviseFilter(Filter f) {
initializationGate();
Set<InternalDistributedMember> recipients = null;
- Profile[] locProfiles = this.profiles; // grab current profiles
+ Profile[] locProfiles = profiles; // grab current profiles
for (Profile profile : locProfiles) {
if (f == null || f.include(profile)) {
if (recipients == null) {
@@ -1185,7 +1186,7 @@ public class DistributionAdvisor {
**/
protected boolean satisfiesFilter(Filter f) {
initializationGate();
- Profile[] locProfiles = this.profiles; // grab current profiles
+ Profile[] locProfiles = profiles; // grab current profiles
for (Profile p : locProfiles) {
if (f.include(p)) {
return true;
@@ -1237,7 +1238,7 @@ public class DistributionAdvisor {
*/
public <T> boolean accept(ProfileVisitor<T> visitor, T aggregate) {
initializationGate();
- final Profile[] locProfiles = this.profiles; // grab current profiles
+ final Profile[] locProfiles = profiles; // grab current profiles
final int numProfiles = locProfiles.length;
Profile p;
for (int index = 0; index < numProfiles; ++index) {
@@ -1257,7 +1258,7 @@ public class DistributionAdvisor {
protected List<Profile> fetchProfiles(Filter f) {
initializationGate();
List<Profile> result = null;
- Profile[] locProfiles = this.profiles;
+ Profile[] locProfiles = profiles;
for (Profile profile : locProfiles) {
if (f == null || f.include(profile)) {
if (result == null) {
@@ -1301,18 +1302,18 @@ public class DistributionAdvisor {
int index = indexOfMemberId(p.getId());
if (index >= 0) {
- Profile[] oldProfiles = this.profiles; // volatile read
+ Profile[] oldProfiles = profiles; // volatile read
oldProfiles[index] = p;
- this.profiles = oldProfiles; // volatile write
+ profiles = oldProfiles; // volatile write
return false;
}
// minimize volatile reads by copying ref to local var
- Profile[] snap = this.profiles; // volatile read
+ Profile[] snap = profiles; // volatile read
Profile[] newProfiles = (Profile[]) ArrayUtils.insert(snap, snap.length, p);
Objects.requireNonNull(newProfiles);
- this.profiles = newProfiles; // volatile write
+ profiles = newProfiles; // volatile write
setNumActiveProfiles(newProfiles.length);
return true;
@@ -1327,7 +1328,7 @@ public class DistributionAdvisor {
// try {
int i = indexOfMemberId(id);
if (i >= 0) {
- Profile profileRemoved = this.profiles[i];
+ Profile profileRemoved = profiles[i];
basicRemoveIndex(i);
return profileRemoved;
} else
@@ -1339,7 +1340,7 @@ public class DistributionAdvisor {
private int indexOfMemberId(ProfileId id) {
Assert.assertHoldsLock(this, true);
- Profile[] profs = this.profiles; // volatile read
+ Profile[] profs = profiles; // volatile read
for (int i = 0; i < profs.length; i++) {
Profile p = profs[i];
if (id instanceof InternalDistributedMember) {
@@ -1356,13 +1357,13 @@ public class DistributionAdvisor {
private void basicRemoveIndex(int index) {
Assert.assertHoldsLock(this, true);
// minimize volatile reads by copying ref to local var
- Profile[] oldProfiles = this.profiles; // volatile read
+ Profile[] oldProfiles = profiles; // volatile read
Profile[] newProfiles = new Profile[oldProfiles.length - 1];
System.arraycopy(oldProfiles, 0, newProfiles, 0, index);
System.arraycopy(oldProfiles, index + 1, newProfiles, index, newProfiles.length - index);
- this.profiles = newProfiles; // volatile write
- if (this.numActiveProfiles > 0) {
- this.numActiveProfiles--;
+ profiles = newProfiles; // volatile write
+ if (numActiveProfiles > 0) {
+ numActiveProfiles--;
}
}
@@ -1402,7 +1403,7 @@ public class DistributionAdvisor {
throw new IllegalArgumentException(
"memberId cannot be null");
}
- this.peerMemberId = memberId;
+ peerMemberId = memberId;
this.version = version;
}
@@ -1412,20 +1413,20 @@ public class DistributionAdvisor {
* @since GemFire 5.7
*/
public ProfileId getId() {
- return this.peerMemberId;
+ return peerMemberId;
}
public int getVersion() {
- return this.version;
+ return version;
}
public int getSerialNumber() {
- return this.serialNumber;
+ return serialNumber;
}
@Override
public int hashCode() {
- return this.getId().hashCode();
+ return getId().hashCode();
}
@Override
@@ -1434,7 +1435,7 @@ public class DistributionAdvisor {
return true;
if (obj == null)
return false;
- if (!this.getClass().equals(obj.getClass()))
+ if (!getClass().equals(obj.getClass()))
return false;
return getId().equals(((Profile) obj).getId());
}
@@ -1445,7 +1446,7 @@ public class DistributionAdvisor {
* @since GemFire 5.0
*/
public InternalDistributedMember getDistributedMember() {
- return this.peerMemberId;
+ return peerMemberId;
}
@Override
@@ -1455,17 +1456,17 @@ public class DistributionAdvisor {
@Override
public void toData(DataOutput out) throws IOException {
- InternalDataSerializer.invokeToData(this.peerMemberId, out);
- out.writeInt(this.version);
- out.writeInt(this.serialNumber);
+ InternalDataSerializer.invokeToData(peerMemberId, out);
+ out.writeInt(version);
+ out.writeInt(serialNumber);
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
- this.peerMemberId = new InternalDistributedMember();
- InternalDataSerializer.invokeFromData(this.peerMemberId, in);
- this.version = in.readInt();
- this.serialNumber = in.readInt();
+ peerMemberId = new InternalDistributedMember();
+ InternalDataSerializer.invokeFromData(peerMemberId, in);
+ version = in.readInt();
+ serialNumber = in.readInt();
}
/**
@@ -1526,10 +1527,10 @@ public class DistributionAdvisor {
}
public void fillInToString(StringBuilder sb) {
- sb.append("memberId=").append(this.peerMemberId);
- sb.append("; version=").append(this.version);
- sb.append("; serialNumber=").append(this.serialNumber);
- sb.append("; initialMembershipVersion=").append(this.initialMembershipVersion);
+ sb.append("memberId=").append(peerMemberId);
+ sb.append("; version=").append(version);
+ sb.append("; serialNumber=").append(serialNumber);
+ sb.append("; initialMembershipVersion=").append(initialMembershipVersion);
}
@Override
@@ -1712,8 +1713,8 @@ public class DistributionAdvisor {
private ThreadTrackingOperationMonitor(
DistributionAdvisor distributionAdvisor) {
super(distributionAdvisor);
- this.currentVersionOperationThreads = new HashMap<>();
- this.previousVersionOperationThreads = new HashMap<>();
+ currentVersionOperationThreads = new HashMap<>();
+ previousVersionOperationThreads = new HashMap<>();
}
@Override
diff --git a/geode-core/src/main/java/org/apache/geode/internal/InternalInstantiator.java b/geode-core/src/main/java/org/apache/geode/internal/InternalInstantiator.java
index 8a11436..dcdabab 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/InternalInstantiator.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/InternalInstantiator.java
@@ -12,6 +12,7 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
+
package org.apache.geode.internal;
import java.io.DataInput;
@@ -20,8 +21,6 @@ import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -29,8 +28,8 @@ import org.apache.logging.log4j.Logger;
import org.apache.geode.DataSerializer;
import org.apache.geode.Instantiator;
+import org.apache.geode.annotations.VisibleForTesting;
import org.apache.geode.annotations.internal.MakeNotStatic;
-import org.apache.geode.cache.Cache;
import org.apache.geode.distributed.internal.ClusterDistributionManager;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.distributed.internal.SerialDistributionMessage;
@@ -57,31 +56,33 @@ public class InternalInstantiator {
private static final Logger logger = LogService.getLogger();
- /** Maps Classes to their ids */
/**
* Maps Class names to their Instantiator instance.
*/
@MakeNotStatic
- private static final ConcurrentMap/* <String,Instantiator> */ dsMap = new ConcurrentHashMap();
+ private static final ConcurrentMap<String, Instantiator> dsMap = new ConcurrentHashMap<>();
/** Maps the id of an instantiator to its Instantiator instance */
@MakeNotStatic
- private static final ConcurrentMap/* <Integer,Instantiator|Marker> */ idsToInstantiators =
- new ConcurrentHashMap();
+ private static final ConcurrentMap<Integer, Object> idsToInstantiators =
+ new ConcurrentHashMap<>();
/**
* Maps the name of the instantiated-class to an instance of InstantiatorAttributesHolder.
*/
@MakeNotStatic
private static final ConcurrentHashMap<String, InstantiatorAttributesHolder> classNamesToHolders =
- new ConcurrentHashMap<String, InstantiatorAttributesHolder>();
+ new ConcurrentHashMap<>();
/**
* Maps the id of an instantiator to an instance of InstantiatorAttributesHolder.
*/
@MakeNotStatic
- private static final ConcurrentHashMap<Integer, InstantiatorAttributesHolder> idsToHolders =
- new ConcurrentHashMap<Integer, InstantiatorAttributesHolder>();
+ private static final ConcurrentHashMap<Integer, InstantiatorAttributesHolder> idsToHolders;
+
+ static {
+ idsToHolders = new ConcurrentHashMap<>();
+ }
private static final String SERVER_CONNECTION_THREAD = "ServerConnection";
/////////////////////// Static Methods ///////////////////////
@@ -90,7 +91,7 @@ public class InternalInstantiator {
* Registers an {@code Instantiator} with the data serialization framework.
*/
public static void register(Instantiator instantiator, boolean distribute) {
- // [sumedh] Skip the checkForThread() check if the instantiation has not
+ // Skip the checkForThread() check if the instantiation is not
// to be distributed. This allows instantiations from ServerConnection
// thread in client security plugins, for example. This is particularly
// useful for native clients that do not send a REGISTER_INSTANTIATORS
@@ -109,27 +110,23 @@ public class InternalInstantiator {
*/
private static void _register(Instantiator instantiator, boolean distribute) {
if (instantiator == null) {
- throw new NullPointerException(
- "Cannot register a null Instantiator.");
+ throw new NullPointerException("Cannot register a null Instantiator.");
}
final int classId = instantiator.getId();
if (classId == 0) {
- throw new IllegalArgumentException(
- "Instantiator id cannot be zero");
+ throw new IllegalArgumentException("Instantiator id cannot be zero");
}
Class c = instantiator.getInstantiatedClass();
final String cName = c.getName();
{
int oldId = getClassId(c);
if (oldId != 0 && oldId != classId) {
- throw new IllegalStateException(
- String.format(
- "Class %s is already registered with id %s so it can not be registered with id %s",
-
- new Object[] {c.getName(), Integer.valueOf(oldId), Integer.valueOf(classId)}));
+ throw new IllegalStateException(String.format(
+ "Class %s is already registered with id %s so it can not be registered with id %s",
+ c.getName(), oldId, classId));
}
}
- final Integer idx = Integer.valueOf(classId);
+ final Integer idx = classId;
synchronized (InternalInstantiator.class) {
boolean retry;
@@ -146,13 +143,12 @@ public class InternalInstantiator {
} else {
Class oldClass = ((Instantiator) oldInst).getInstantiatedClass();
if (!oldClass.getName().equals(cName)) {
- throw new IllegalStateException(
- String.format(
- "Class id %s is already registered for class %s so it could not be registered for class %s",
-
- new Object[] {Integer.valueOf(classId), oldClass.getName(), cName}));
+ throw new IllegalStateException(String.format(
+ "Class id %s is already registered for class %s so it could not be registered for class %s",
+ classId, oldClass.getName(), cName));
} else {
- return; // it was already registered
+ // it was already registered
+ return;
}
}
} else {
@@ -160,36 +156,38 @@ public class InternalInstantiator {
}
} while (retry);
- // if instantiator is getting registered for first time
- // its EventID will be null, so generate a new event id
- // the the distributed system is connected
- InternalCache cache = GemFireCacheImpl.getInstance();
- if (cache != null && instantiator.getEventId() == null) {
- instantiator.setEventId(new EventID(cache.getDistributedSystem()));
- }
+ setEventIdIfNew(instantiator);
- logger
- .info("Instantiator registered with id {} class {}",
- Integer.valueOf(classId), c.getName());
+ logger.info("Instantiator registered with id {} class {}", classId, c.getName());
}
- if (distribute) { // originated in this VM
- // send a message to other peers telling them about a newly-registered
- // instantiator, it also send event id of the originator along with the
- // instantiator
+ if (distribute) {
+ // originated in this VM
sendRegistrationMessage(instantiator);
- // send it to cache servers if it is a client
sendRegistrationMessageToServers(instantiator);
}
- // send it to all cache clients irrelevant of distribute
- // cache servers send it all the clients irrelevant of
- // originator VM
sendRegistrationMessageToClients(instantiator);
InternalDataSerializer.fireNewInstantiator(instantiator);
}
/**
+ * if instantiator is getting registered for first time its EventID will be null, so generate a
+ * new event id the the distributed system is connected
+ */
+ private static void setEventIdIfNew(final Instantiator instantiator) {
+ final InternalCache cache = getInternalCache();
+ if (cache != null && instantiator.getEventId() == null) {
+ instantiator.setEventId(new EventID(cache.getDistributedSystem()));
+ }
+ }
+
+ @SuppressWarnings("deprecation")
+ private static InternalCache getInternalCache() {
+ return GemFireCacheImpl.getInstance();
+ }
+
+ /**
* On receving on client, when the instantiator gets loaded, and if it has static initializer
* which registers instantiators having distribute flag as true. And as distribute flag is true,
* client sends instantiator registartion recursively to server. Similarly, on server side, when
@@ -207,12 +205,10 @@ public class InternalInstantiator {
* Sets the EventID to the instantiator if distributed system is created
*/
public static EventID generateEventId() {
- InternalCache cache = GemFireCacheImpl.getInstance();
- if (cache == null) {
- // A cache has not yet created
- return null;
+ if (isCacheCreated()) {
+ return new EventID(InternalDistributedSystem.getAnyInstance());
}
- return new EventID(InternalDistributedSystem.getAnyInstance());
+ return null;
}
/**
@@ -235,10 +231,7 @@ public class InternalInstantiator {
* Sends Instantiator registration message to all cache clients
*/
private static void sendRegistrationMessageToClients(Instantiator instantiator) {
- Cache cache = GemFireCacheImpl.getInstance();
- if (cache == null) {
- // A cache has not yet been created.
- // we can't propagate it to clients
+ if (!isCacheCreated()) {
return;
}
byte[][] serializedInstantiators = new byte[3][];
@@ -265,6 +258,10 @@ public class InternalInstantiator {
CacheClientNotifier.routeClientMessage(clientInstantiatorMessage);
}
+ private static boolean isCacheCreated() {
+ return getInternalCache() != null;
+ }
+
/**
* Creates a new {@code Instantiator} with the given class and id and
* {@linkplain #register(Instantiator, boolean) registers} it with the data serialization
@@ -333,7 +330,7 @@ public class InternalInstantiator {
private static void register(String instantiatorClassName, InstantiatorAttributesHolder holder,
boolean distribute) {
- Object inst = null;
+ Object inst;
synchronized (InternalInstantiator.class) {
inst = idsToInstantiators.get(holder.getId());
if (inst == null) {
@@ -341,25 +338,21 @@ public class InternalInstantiator {
throw new IllegalArgumentException("Instantiator class name cannot be null or empty.");
}
if (holder.getId() == 0) {
- throw new IllegalArgumentException(
- "Instantiator id cannot be zero");
+ throw new IllegalArgumentException("Instantiator id cannot be zero");
}
InstantiatorAttributesHolder iah =
classNamesToHolders.putIfAbsent(holder.getInstantiatedClassName(), holder);
if (iah != null && iah.getId() != holder.getId()) {
- throw new IllegalStateException(
- String.format(
- "Class %s is already registered with id %s so it can not be registered with id %s",
-
- new Object[] {instantiatorClassName, iah.getId(), holder.getId()}));
+ throw new IllegalStateException(String.format(
+ "Class %s is already registered with id %s so it can not be registered with id %s",
+ instantiatorClassName, iah.getId(), holder.getId()));
}
idsToHolders.putIfAbsent(holder.getId(), holder);
- logger.info("Instantiator registered with holder id {} class {}",
- Integer.valueOf(holder.getId()),
+ logger.info("Instantiator registered with holder id {} class {}", holder.getId(),
holder.getInstantiatedClassName());
if (distribute) {
@@ -372,18 +365,12 @@ public class InternalInstantiator {
if (inst instanceof Marker) {
Class instantiatorClass = null, instantiatedClass = null;
try {
- // fix bug 46355, need to move getCachedClass() outside of sync
instantiatorClass =
InternalDataSerializer.getCachedClass(holder.getInstantiatorClassName());
instantiatedClass =
InternalDataSerializer.getCachedClass(holder.getInstantiatedClassName());
- } catch (ClassNotFoundException cnfe) {
- InternalCache cache = GemFireCacheImpl.getInstance();
- if (cache != null && cache.getLogger() != null && cache.getLogger().infoEnabled()) {
- cache.getLogger().info(
- String.format("Could not load instantiator class: %s",
- new Object[] {cnfe.getMessage()}));
- }
+ } catch (ClassNotFoundException e) {
+ logClassNotFoundException(e);
}
synchronized (InternalInstantiator.class) {
Object inst2 = idsToInstantiators.get(holder.getId());
@@ -392,17 +379,21 @@ public class InternalInstantiator {
holder.getEventId(), holder.getContext());
} else {
if (inst2 == null || inst2 instanceof Marker) {
- // recurse
register(instantiatorClassName, holder, distribute);
- } else {
- // already registered
- return;
}
}
}
}
}
+ private static void logClassNotFoundException(final ClassNotFoundException e) {
+ final InternalCache cache = getInternalCache();
+ if (cache != null && cache.getLogger() != null && cache.getLogger().infoEnabled()) {
+ cache.getLogger()
+ .info(String.format("Could not load instantiator class: %s", e.getMessage()));
+ }
+ }
+
public static class InstantiatorAttributesHolder {
private String instantiatorName;
private String instantiatedName;
@@ -410,17 +401,17 @@ public class InternalInstantiator {
private EventID eventId;
private ClientProxyMembershipID context;
- public InstantiatorAttributesHolder(String instantiatorClass, String instantiatedClass,
+ InstantiatorAttributesHolder(String instantiatorClass, String instantiatedClass,
int id) {
- this.instantiatorName = instantiatorClass;
- this.instantiatedName = instantiatedClass;
+ instantiatorName = instantiatorClass;
+ instantiatedName = instantiatedClass;
this.id = id;
}
- public InstantiatorAttributesHolder(String instantiatorClass, String instantiatedClass, int id,
+ InstantiatorAttributesHolder(String instantiatorClass, String instantiatedClass, int id,
EventID eventId, ClientProxyMembershipID context) {
- this.instantiatorName = instantiatorClass;
- this.instantiatedName = instantiatedClass;
+ instantiatorName = instantiatorClass;
+ instantiatedName = instantiatedClass;
this.id = id;
this.eventId = eventId;
this.context = context;
@@ -447,10 +438,10 @@ public class InternalInstantiator {
}
public String toString() {
- return "InstantiatorAttributesHolder[irName=" + this.instantiatorName + ",idName="
- + this.instantiatedName + ",id=" + this.id
- + (this.eventId != null ? ",this.eventId=" + this.eventId : "")
- + (this.context != null ? ",this.context=" + this.context : "") + "]";
+ return "InstantiatorAttributesHolder[irName=" + instantiatorName + ",idName="
+ + instantiatedName + ",id=" + id
+ + (eventId != null ? ",this.eventId=" + eventId : "")
+ + (context != null ? ",this.context=" + context : "") + "]";
}
}
@@ -466,12 +457,11 @@ public class InternalInstantiator {
throw new NullPointerException(
"Cannot unregister a null class");
}
- final Integer idx = Integer.valueOf(classId);
+ final Integer idx = classId;
final Instantiator i = (Instantiator) idsToInstantiators.remove(idx);
if (i == null) {
throw new IllegalArgumentException(
- String.format("Class %s was not registered with id %s",
- new Object[] {c.getName(), Integer.valueOf(classId)}));
+ String.format("Class %s was not registered with id %s", c.getName(), classId));
} else {
dsMap.remove(c.getName(), i);
}
@@ -479,7 +469,10 @@ public class InternalInstantiator {
classNamesToHolders.remove(i.getInstantiatedClass().getName());
}
- // testhook that removes all registed instantiators
+ /**
+ * testhook that removes all registed instantiators
+ */
+ @VisibleForTesting
public static void reinitialize() {
idsToInstantiators.clear();
dsMap.clear();
@@ -496,7 +489,7 @@ public class InternalInstantiator {
*/
public static int getClassId(Class c) {
int result = 0;
- final Instantiator i = (Instantiator) dsMap.get(c.getName());
+ final Instantiator i = dsMap.get(c.getName());
if (i != null) {
result = i.getId();
} else {
@@ -514,7 +507,7 @@ public class InternalInstantiator {
* @see DataSerializer#readObject
*/
public static Instantiator getInstantiator(int classId) {
- final Integer idx = Integer.valueOf(classId);
+ final Integer idx = classId;
Marker marker;
boolean retry;
Object o = idsToInstantiators.get(idx);
@@ -554,13 +547,8 @@ public class InternalInstantiator {
idsToHolders.remove(classId);
instantiator = (Instantiator) idsToInstantiators.get(classId);
}
- } catch (ClassNotFoundException cnfe) {
- InternalCache cache = GemFireCacheImpl.getInstance();
- if (cache != null && cache.getLogger() != null
- && cache.getLogger().infoEnabled()) {
- cache.getLogger().info(
- String.format("Could not load instantiator class: %s", cnfe.getMessage()));
- }
+ } catch (ClassNotFoundException e) {
+ logClassNotFoundException(e);
}
}
return instantiator;
@@ -574,7 +562,7 @@ public class InternalInstantiator {
private static void sendRegistrationMessage(Instantiator s) {
InternalDistributedSystem system = InternalDistributedSystem.getAnyInstance();
if (system != null) {
- RegistrationMessage m = null;
+ RegistrationMessage m;
if (s.getContext() == null) {
m = new RegistrationMessage(s);
} else {
@@ -593,8 +581,8 @@ public class InternalInstantiator {
*
* @throws IllegalArgumentException If the class can't be instantiated
*/
- protected static Instantiator newInstance(Class instantiatorClass, Class instantiatedClass,
- int id) {
+ protected static Instantiator newInstance(Class<?> instantiatorClass, Class<?> instantiatedClass,
+ int id) throws IllegalArgumentException {
if (!Instantiator.class.isAssignableFrom(instantiatorClass)) {
throw new IllegalArgumentException(
String.format("%s does not extend Instantiator.",
@@ -603,70 +591,60 @@ public class InternalInstantiator {
Constructor init;
boolean intConstructor = false;
- Class[] types;
try {
- types = new Class[] {Class.class, int.class};
- init = instantiatorClass.getDeclaredConstructor(types);
+ init = instantiatorClass.getDeclaredConstructor(Class.class, int.class);
intConstructor = true;
} catch (NoSuchMethodException ex) {
// for backwards compat check for (Class, byte)
try {
- types = new Class[] {Class.class, byte.class};
- init = instantiatorClass.getDeclaredConstructor(types);
+ init = instantiatorClass.getDeclaredConstructor(Class.class, byte.class);
} catch (NoSuchMethodException ex2) {
if (instantiatorClass.getDeclaringClass() != null) {
- String msg = String.format(
+ throw new IllegalArgumentException(String.format(
"Class %s does not have a two-argument (Class, int) constructor. It is an inner class of %s. Should it be a static inner class?",
- instantiatorClass.getName(), instantiatorClass.getDeclaringClass());
- throw new IllegalArgumentException(msg);
+ instantiatorClass.getName(), instantiatorClass.getDeclaringClass()));
}
- String msg = String.format(
- "Class %s does not have a two-argument (Class, int) constructor.",
- instantiatorClass.getName());
- throw new IllegalArgumentException(msg);
+ throw new IllegalArgumentException(
+ String.format("Class %s does not have a two-argument (Class, int) constructor.",
+ instantiatorClass.getName()));
}
}
Instantiator s;
try {
init.setAccessible(true);
- Object[] args = new Object[] {instantiatedClass,
- intConstructor ? (Object) Integer.valueOf(id) : (Object) Byte.valueOf((byte) id)};
- s = (Instantiator) init.newInstance(args);
-
+ s = (Instantiator) init.newInstance(instantiatedClass, convertId(id, intConstructor));
} catch (IllegalAccessException ex) {
- throw new IllegalArgumentException(
- String.format("Could not access zero-argument constructor of %s",
- instantiatorClass.getName()));
+ throw new IllegalArgumentException(String
+ .format("Could not access zero-argument constructor of %s", instantiatorClass.getName()));
} catch (InstantiationException ex) {
- RuntimeException ex2 = new IllegalArgumentException(
- String.format("Could not instantiate an instance of %s",
- instantiatorClass.getName()));
- ex2.initCause(ex);
- throw ex2;
+ throw new IllegalArgumentException(
+ String.format("Could not instantiate an instance of %s", instantiatorClass.getName()),
+ ex);
} catch (InvocationTargetException ex) {
- RuntimeException ex2 = new IllegalArgumentException(
- String.format("While instantiating an instance of %s",
- instantiatorClass.getName()));
- ex2.initCause(ex);
- throw ex2;
+ throw new IllegalArgumentException(
+ String.format("While instantiating an instance of %s", instantiatorClass.getName()), ex);
}
return s;
}
+ private static Object convertId(int id, boolean asInteger) {
+ if (asInteger) {
+ return id;
+ }
+ return (byte) id;
+ }
+
/**
* Returns all of the currently registered instantiators
*/
public static Instantiator[] getInstantiators() {
- Collection coll = new ArrayList();
if (!classNamesToHolders.isEmpty()) {
- Iterator it = classNamesToHolders.values().iterator();
- while (it.hasNext()) {
+ for (InstantiatorAttributesHolder holder : classNamesToHolders.values()) {
try {
- InstantiatorAttributesHolder holder = (InstantiatorAttributesHolder) it.next();
Class instantiatorClass =
InternalDataSerializer.getCachedClass(holder.getInstantiatorClassName());
Class instantiatedClass =
@@ -679,19 +657,12 @@ public class InternalInstantiator {
classNamesToHolders.remove(holder.getInstantiatedClassName());
idsToHolders.remove(holder.getId());
}
- } catch (ClassNotFoundException cnfe) {
- InternalCache cache = GemFireCacheImpl.getInstance();
- if (cache != null && cache.getLogger() != null
- && cache.getLogger().infoEnabled()) {
- cache.getLogger().info(
- String.format("Could not load instantiator class: %s",
- cnfe.getMessage()));
- }
+ } catch (ClassNotFoundException e) {
+ logClassNotFoundException(e);
}
}
}
- coll.addAll(dsMap.values()); // Don't move it before the if block above.
- return (Instantiator[]) coll.toArray(new Instantiator[coll.size()]);
+ return dsMap.values().toArray(new Instantiator[0]);
}
/**
@@ -700,21 +671,12 @@ public class InternalInstantiator {
* @return array of InstantiatorAttributesArray instances.
*/
public static Object[] getInstantiatorsForSerialization() {
- Collection coll = new ArrayList(dsMap.size() + idsToHolders.size());
- coll.addAll(dsMap.values());
- coll.addAll(classNamesToHolders.values()); // TODO (ashetkar) will it add duplicates?
- return coll.toArray(new Object[coll.size()]);
- }
-
- public static int getIdsToHoldersSize() {
- return idsToHolders.size();
+ ArrayList<Object> instantiators = new ArrayList<>(dsMap.size() + idsToHolders.size());
+ instantiators.addAll(dsMap.values());
+ instantiators.addAll(classNamesToHolders.values());
+ return instantiators.toArray();
}
- public static int getNamesToHoldersSize() {
- return classNamesToHolders.size();
- }
- /////////////////////// Inner Classes ///////////////////////
-
/**
* A marker object for {@code Instantiator}s that have not been registered. Using this marker
* object allows us to asynchronously send {@code Instantiator} registration updates. If the
@@ -741,9 +703,9 @@ public class InternalInstantiator {
*/
Instantiator getInstantiator() {
synchronized (this) {
- if (this.instantiator == null) {
+ if (instantiator == null) {
try {
- this.wait(InternalDataSerializer.GetMarker.WAIT_MS);
+ wait(InternalDataSerializer.GetMarker.WAIT_MS);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
// just return null, let it fail.
@@ -751,7 +713,7 @@ public class InternalInstantiator {
}
}
- return this.instantiator;
+ return instantiator;
}
}
@@ -762,50 +724,8 @@ public class InternalInstantiator {
void setInstantiator(Instantiator instantiator) {
synchronized (this) {
this.instantiator = instantiator;
- this.notifyAll();
- }
- }
- }
-
- /**
- * Persist this class's map to out
- */
- public static void saveRegistrations(DataOutput out) throws IOException {
- for (Instantiator inst : InternalInstantiator.getInstantiators()) {
- out.writeInt(inst.getId());
- DataSerializer.writeClass(inst.getClass(), out);
- DataSerializer.writeClass(inst.getInstantiatedClass(), out);
- }
- // We know that Instantiator id's must not be 0 so write a zero
- // to mark then end of the instantiators.
- out.writeInt(0);
- }
-
- /**
- * Read the data from in and register it with this class.
- *
- * @throws IllegalArgumentException if a registration fails
- */
- public static void loadRegistrations(DataInput in) throws IOException {
- int instId;
- while ((instId = in.readInt()) != 0) {
- Class instClass = null;
- Class instantiatedClass = null;
- boolean skip = false;
- try {
- instClass = DataSerializer.readClass(in);
- } catch (ClassNotFoundException ex) {
- skip = true;
- }
- try {
- instantiatedClass = DataSerializer.readClass(in);
- } catch (ClassNotFoundException ex) {
- skip = true;
- }
- if (skip) {
- continue;
+ notifyAll();
}
- register(newInstance(instClass, instantiatedClass, instId), true);
}
}
@@ -817,10 +737,10 @@ public class InternalInstantiator {
/**
* The {@code Instantiator} class that was registered
*/
- protected Class instantiatorClass;
+ Class instantiatorClass;
/** The class that is instantiated by the instantiator */
- protected Class instantiatedClass;
+ Class instantiatedClass;
/**
* The id of the {@code Instantiator} that was registered
@@ -835,15 +755,15 @@ public class InternalInstantiator {
/**
* Problems encountered while running fromData. See bug 31573.
*/
- protected transient StringBuffer fromDataProblems;
+ transient StringBuffer fromDataProblems;
/**
* The name of the {@code Instantiator} class that was registered
*/
- protected String instantiatorClassName;
+ String instantiatorClassName;
/** Name of the class that is instantiated by the instantiator */
- protected String instantiatedClassName;
+ String instantiatedClassName;
/**
* Constructor for {@code DataSerializable}
@@ -857,27 +777,27 @@ public class InternalInstantiator {
* was registered.
*/
public RegistrationMessage(Instantiator s) {
- this.instantiatorClass = s.getClass();
- this.instantiatedClass = s.getInstantiatedClass();
- this.id = s.getId();
- this.eventId = (EventID) s.getEventId();
+ instantiatorClass = s.getClass();
+ instantiatedClass = s.getInstantiatedClass();
+ id = s.getId();
+ eventId = (EventID) s.getEventId();
}
@Override
protected void process(ClusterDistributionManager dm) {
- if (this.fromDataProblems != null) {
+ if (fromDataProblems != null) {
if (logger.isDebugEnabled()) {
- logger.debug(this.fromDataProblems);
+ logger.debug(fromDataProblems);
}
}
- if (this.instantiatorClass != null && this.instantiatedClass != null) {
- Instantiator s = newInstance(this.instantiatorClass, this.instantiatedClass, this.id);
+ if (instantiatorClass != null && instantiatedClass != null) {
+ Instantiator s = newInstance(instantiatorClass, instantiatedClass, id);
s.setEventId(eventId);
InternalInstantiator.register(s, false);
- } else if (this.instantiatorClassName != null && this.instantiatedClassName != null) {
- InternalInstantiator.register(this.instantiatorClassName, this.instantiatedClassName,
- this.id, false, this.eventId, null);
+ } else if (instantiatorClassName != null && instantiatedClassName != null) {
+ InternalInstantiator.register(instantiatorClassName, instantiatedClassName,
+ id, false, eventId, null);
}
}
@@ -889,66 +809,57 @@ public class InternalInstantiator {
@Override
public void toData(DataOutput out) throws IOException {
super.toData(out);
- DataSerializer.writeNonPrimitiveClassName(this.instantiatorClass.getName(), out);
- DataSerializer.writeNonPrimitiveClassName(this.instantiatedClass.getName(), out);
- out.writeInt(this.id);
- DataSerializer.writeObject(this.eventId, out);
+ DataSerializer.writeNonPrimitiveClassName(instantiatorClass.getName(), out);
+ DataSerializer.writeNonPrimitiveClassName(instantiatedClass.getName(), out);
+ out.writeInt(id);
+ DataSerializer.writeObject(eventId, out);
}
private void recordFromDataProblem(String s) {
- if (this.fromDataProblems == null) {
- this.fromDataProblems = new StringBuffer();
+ if (fromDataProblems == null) {
+ fromDataProblems = new StringBuffer();
}
- this.fromDataProblems.append(s);
- this.fromDataProblems.append("\n\n");
+ fromDataProblems.append(s);
+ fromDataProblems.append("\n\n");
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
super.fromData(in);
- this.instantiatorClassName = DataSerializer.readNonPrimitiveClassName(in);
- this.instantiatedClassName = DataSerializer.readNonPrimitiveClassName(in);
+ instantiatorClassName = DataSerializer.readNonPrimitiveClassName(in);
+ instantiatedClassName = DataSerializer.readNonPrimitiveClassName(in);
if (CacheClientNotifier.getInstance() != null) {
// This is a server so we need to send the instantiator to clients
// right away. For that we need to load the class as the constructor of
// ClientDataSerializerMessage requires instantiated class.
try {
- this.instantiatorClass =
- InternalDataSerializer.getCachedClass(this.instantiatorClassName); // fix for bug
- // 41206
+ instantiatorClass = InternalDataSerializer.getCachedClass(instantiatorClassName);
} catch (ClassNotFoundException ex) {
- recordFromDataProblem(
- String.format("Could not load instantiator class: %s",
- ex));
- this.instantiatorClass = null;
+ recordFromDataProblem(String.format("Could not load instantiator class: %s", ex));
+ instantiatorClass = null;
}
try {
- this.instantiatedClass =
- InternalDataSerializer.getCachedClass(this.instantiatedClassName); // fix for bug
- // 41206
+ instantiatedClass = InternalDataSerializer.getCachedClass(instantiatedClassName);
} catch (ClassNotFoundException ex) {
- recordFromDataProblem(
- String.format("Could not load instantiated class: %s",
- ex));
- this.instantiatedClass = null;
+ recordFromDataProblem(String.format("Could not load instantiated class: %s", ex));
+ instantiatedClass = null;
}
}
- this.id = in.readInt();
- this.eventId = (EventID) DataSerializer.readObject(in);
+ id = in.readInt();
+ eventId = DataSerializer.readObject(in);
}
@Override
public String toString() {
- String instatiatorName = (this.instantiatorClass == null) ? this.instantiatorClassName
- : this.instantiatorClass.getName();
- String instatiatedName = (this.instantiatedClass == null) ? this.instantiatedClassName
- : this.instantiatedClass.getName();
- return String.format("Register Instantiator %s of class %s that instantiates a %s",
-
- new Object[] {Integer.valueOf(this.id), instatiatorName, instatiatedName});
+ String instatiatorName = (instantiatorClass == null) ? instantiatorClassName
+ : instantiatorClass.getName();
+ String instatiatedName = (instantiatedClass == null) ? instantiatedClassName
+ : instantiatedClass.getName();
+ return String.format("Register Instantiator %s of class %s that instantiates a %s", id,
+ instatiatorName, instatiatedName);
}
}
@@ -975,11 +886,11 @@ public class InternalInstantiator {
* {@code Instantiator} was registered.
*/
public RegistrationContextMessage(Instantiator s) {
- this.instantiatorClass = s.getClass();
- this.instantiatedClass = s.getInstantiatedClass();
- this.id = s.getId();
- this.eventId = (EventID) s.getEventId();
- this.context = (ClientProxyMembershipID) s.getContext();
+ instantiatorClass = s.getClass();
+ instantiatedClass = s.getInstantiatedClass();
+ id = s.getId();
+ eventId = (EventID) s.getEventId();
+ context = (ClientProxyMembershipID) s.getContext();
}
@Override
@@ -989,14 +900,14 @@ public class InternalInstantiator {
logger.debug(fromDataProblems);
}
}
- if (this.instantiatorClass != null && this.instantiatedClass != null) {
- Instantiator s = newInstance(this.instantiatorClass, this.instantiatedClass, this.id);
- s.setEventId(this.eventId);
- s.setContext(this.context);
+ if (instantiatorClass != null && instantiatedClass != null) {
+ Instantiator s = newInstance(instantiatorClass, instantiatedClass, id);
+ s.setEventId(eventId);
+ s.setContext(context);
InternalInstantiator.register(s, false);
- } else if (this.instantiatorClassName != null && this.instantiatedClassName != null) {
- InternalInstantiator.register(this.instantiatorClassName, this.instantiatedClassName,
- this.id, false, this.eventId, this.context);
+ } else if (instantiatorClassName != null && instantiatedClassName != null) {
+ InternalInstantiator.register(instantiatorClassName, instantiatedClassName,
+ id, false, eventId, context);
}
}
@@ -1008,31 +919,25 @@ public class InternalInstantiator {
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
super.fromData(in);
- this.context = ClientProxyMembershipID.readCanonicalized(in);
+ context = ClientProxyMembershipID.readCanonicalized(in);
}
@Override
public void toData(DataOutput out) throws IOException {
super.toData(out);
- DataSerializer.writeObject(this.context, out);
+ DataSerializer.writeObject(context, out);
}
}
public static void logInstantiators() {
- for (Iterator itr = dsMap.values().iterator(); itr.hasNext();) {
- Instantiator instantiator = (Instantiator) itr.next();
-
- logger
- .info("Instantiator registered with id {} class {}",
- Integer.valueOf(instantiator.getId()),
- instantiator.getInstantiatedClass().getName());
+ for (Instantiator instantiator : dsMap.values()) {
+ logger.info("Instantiator registered with id {} class {}", instantiator.getId(),
+ instantiator.getInstantiatedClass().getName());
}
- for (Iterator itr = idsToHolders.values().iterator(); itr.hasNext();) {
- InstantiatorAttributesHolder holder = (InstantiatorAttributesHolder) itr.next();
-
- logger.info("Instantiator registered with holder id {} class {}",
- Integer.valueOf(holder.getId()), holder.getInstantiatedClassName());
+ for (InstantiatorAttributesHolder holder : idsToHolders.values()) {
+ logger.info("Instantiator registered with holder id {} class {}", holder.getId(),
+ holder.getInstantiatedClassName());
}
}
diff --git a/geode-core/src/main/java/org/apache/geode/internal/SetUtils.java b/geode-core/src/main/java/org/apache/geode/internal/SetUtils.java
deleted file mode 100644
index 3587d88..0000000
--- a/geode-core/src/main/java/org/apache/geode/internal/SetUtils.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.internal;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-/**
- * Utility methods for managing and using Sets
- *
- * @since GemFire 59poc
- *
- */
-public class SetUtils {
- public static <T> boolean intersectsWith(final Set<? extends T> a, final Set<? extends T> b) {
- if (a == b) {
- return true;
- }
- final Set/* <T> */ lSet, sSet;
- if (a.size() >= b.size()) {
- lSet = a;
- sSet = b;
- } else {
- lSet = b;
- sSet = a;
- }
- for (Iterator i = sSet.iterator(); i.hasNext();) {
- Object item = i.next();
- if (lSet.contains(item)) {
- return true;
- }
- }
- return false;
- }
-
- public static /* T */ Set/* <T> */ intersection(final Set/* <T> */ a, final Set/* <T> */ b) {
- if (a == b) {
- return a;
- }
- final Set/* <T> */ lSet, sSet;
- if (a.size() >= b.size()) {
- lSet = a;
- sSet = b;
- } else {
- lSet = b;
- sSet = a;
- }
- HashSet /* <T> */ ret = new HashSet/* <T> */();
- for (Iterator i = sSet.iterator(); i.hasNext();) {
- Object item = i.next();
- if (lSet.contains(item)) {
- ret.add(item);
- }
- }
- return ret;
- }
-}
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/BucketAdvisor.java b/geode-core/src/main/java/org/apache/geode/internal/cache/BucketAdvisor.java
index f9345a4..9112184 100755
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/BucketAdvisor.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/BucketAdvisor.java
@@ -12,6 +12,7 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
+
package org.apache.geode.internal.cache;
import java.io.DataInput;
@@ -45,6 +46,7 @@ import org.apache.geode.annotations.Immutable;
import org.apache.geode.cache.RegionDestroyedException;
import org.apache.geode.cache.client.internal.locator.SerializationHelper;
import org.apache.geode.cache.partition.PartitionListener;
+import org.apache.geode.cache.server.CacheServer;
import org.apache.geode.distributed.DistributedLockService;
import org.apache.geode.distributed.DistributedSystemDisconnectedException;
import org.apache.geode.distributed.LockNotHeldException;
@@ -75,18 +77,18 @@ import org.apache.geode.internal.util.StopWatch;
public class BucketAdvisor extends CacheDistributionAdvisor {
private static final Logger logger = LogService.getLogger();
- public static final boolean ENFORCE_SAFE_CLOSE = false;
+ private static final boolean ENFORCE_SAFE_CLOSE = false;
// TODO: Boolean.getBoolean("gemfire.BucketAdvisor.debug.enforceSafeClose");
/** Reference to the InternalDistributedMember that is primary. */
- private final AtomicReference primaryMember = new AtomicReference();
+ private final AtomicReference<InternalDistributedMember> primaryMember = new AtomicReference<>();
/**
* Advice requests for {@link #adviseProfileUpdate()} delegate to the partitioned region's
* <code>RegionAdvisor</code> to include members with {@link ProxyBucketRegion}s as well as real
* {@link BucketRegion}s.
*/
- protected final RegionAdvisor regionAdvisor;
+ private final RegionAdvisor regionAdvisor;
private final BucketRedundancyTracker redundancyTracker;
@@ -168,8 +170,8 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
private BucketAdvisor(Bucket bucket, RegionAdvisor regionAdvisor) {
super(bucket);
this.regionAdvisor = regionAdvisor;
- this.pRegion = this.regionAdvisor.getPartitionedRegion();
- this.redundancyTracker =
+ pRegion = this.regionAdvisor.getPartitionedRegion();
+ redundancyTracker =
new BucketRedundancyTracker(pRegion.getRedundantCopies(), pRegion.getRedundancyTracker());
resetParentAdvisor(bucket.getId());
}
@@ -180,25 +182,25 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
return advisor;
}
- public void resetParentAdvisor(int bucketId) {
- PartitionedRegion colocatedRegion = ColocationHelper.getColocatedRegion(this.pRegion);
+ private void resetParentAdvisor(int bucketId) {
+ PartitionedRegion colocatedRegion = ColocationHelper.getColocatedRegion(pRegion);
if (colocatedRegion != null) {
if (colocatedRegion.isFixedPartitionedRegion()) {
List<FixedPartitionAttributesImpl> fpas = colocatedRegion.getFixedPartitionAttributesImpl();
if (fpas != null) {
for (FixedPartitionAttributesImpl fpa : fpas) {
if (fpa.hasBucket(bucketId)) {
- this.parentAdvisor =
+ parentAdvisor =
colocatedRegion.getRegionAdvisor().getBucketAdvisor(fpa.getStartingBucketID());
break;
}
}
}
} else {
- this.parentAdvisor = colocatedRegion.getRegionAdvisor().getBucketAdvisor(bucketId);
+ parentAdvisor = colocatedRegion.getRegionAdvisor().getBucketAdvisor(bucketId);
}
} else {
- this.parentAdvisor = null;
+ parentAdvisor = null;
}
}
@@ -207,13 +209,13 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// already assigned
return;
}
- if (this.pRegion.isFixedPartitionedRegion()) {
- List<FixedPartitionAttributesImpl> fpas = this.pRegion.getFixedPartitionAttributesImpl();
+ if (pRegion.isFixedPartitionedRegion()) {
+ List<FixedPartitionAttributesImpl> fpas = pRegion.getFixedPartitionAttributesImpl();
if (fpas != null) {
int bucketId = getBucket().getId();
for (FixedPartitionAttributesImpl fpa : fpas) {
if (fpa.hasBucket(bucketId) && bucketId != fpa.getStartingBucketID()) {
- startingBucketAdvisor = this.regionAdvisor.getBucketAdvisor(fpa.getStartingBucketID());
+ startingBucketAdvisor = regionAdvisor.getBucketAdvisor(fpa.getStartingBucketID());
break;
}
}
@@ -248,12 +250,12 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* Try to lock the primary bucket to make sure no operation is on-going at current bucket.
*
*/
- public void tryLockIfPrimary() {
+ void tryLockIfPrimary() {
if (isPrimary()) {
try {
- this.primaryMoveWriteLock.lock();
+ primaryMoveWriteLock.lock();
} finally {
- this.primaryMoveWriteLock.unlock();
+ primaryMoveWriteLock.unlock();
}
}
}
@@ -266,7 +268,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*/
public boolean deposePrimary() {
if (isPrimary()) {
- this.primaryMoveWriteLock.lock();
+ primaryMoveWriteLock.lock();
boolean needToSendProfileUpdate = false;
try {
removePrimary(getDistributionManager().getId());
@@ -280,7 +282,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
}
}
} finally {
- this.primaryMoveWriteLock.unlock();
+ primaryMoveWriteLock.unlock();
if (needToSendProfileUpdate) {
sendProfileUpdate();
}
@@ -299,16 +301,10 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* <p>
* Caller must synchronize on this BucketAdvisor.
*
- * @return true if children were all deposed as primaries
- * @guarded.By this
*/
- private boolean deposePrimaryForColocatedChildren() {
+ private void deposePrimaryForColocatedChildren() {
boolean deposedChildPrimaries = true;
-
- // getColocatedChildRegions returns only the child PRs directly colocated
- // with thisPR...
- List<PartitionedRegion> colocatedChildPRs =
- ColocationHelper.getColocatedChildRegions(this.pRegion);
+ List<PartitionedRegion> colocatedChildPRs = ColocationHelper.getColocatedChildRegions(pRegion);
if (colocatedChildPRs != null) {
for (PartitionedRegion pr : colocatedChildPRs) {
Bucket b = pr.getRegionAdvisor().getBucket(getBucket().getId());
@@ -323,13 +319,12 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
}
}
}
- return deposedChildPrimaries;
}
- private boolean deposeOtherPrimaryBucketForFixedPartition() {
+ private void deposeOtherPrimaryBucketForFixedPartition() {
boolean deposedOtherPrimaries = true;
int bucketId = getBucket().getId();
- List<FixedPartitionAttributesImpl> fpas = this.pRegion.getFixedPartitionAttributesImpl();
+ List<FixedPartitionAttributesImpl> fpas = pRegion.getFixedPartitionAttributesImpl();
if (fpas != null) {
for (FixedPartitionAttributesImpl fpa : fpas) {
if (fpa.getStartingBucketID() == bucketId) {
@@ -340,12 +335,9 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
deposedOtherPrimaries = ba.deposePrimary() && deposedOtherPrimaries;
}
}
- } else {
- continue;
}
}
}
- return deposedOtherPrimaries;
}
void removeBucket() {
@@ -365,7 +357,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
return getDistributionManager().getId();
}
- Profile locProfiles[] = this.profiles; // volatile read
+ Profile[] locProfiles = profiles; // volatile read
if (locProfiles.length == 0) {
return null;
}
@@ -385,8 +377,8 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*
* @return the queue of primary volunteering tasks
*/
- Queue getVolunteeringQueue() {
- return this.regionAdvisor.getVolunteeringQueue();
+ private Queue<Runnable> getVolunteeringQueue() {
+ return regionAdvisor.getVolunteeringQueue();
}
/**
@@ -395,8 +387,8 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*
* @return the semaphore which controls the number of volunteering threads
*/
- Semaphore getVolunteeringSemaphore() {
- return this.regionAdvisor.getVolunteeringSemaphore();
+ private Semaphore getVolunteeringSemaphore() {
+ return regionAdvisor.getVolunteeringSemaphore();
}
/**
@@ -404,8 +396,8 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*
* @return the PartitionedRegionStats
*/
- PartitionedRegionStats getPartitionedRegionStats() {
- return this.regionAdvisor.getPartitionedRegionStats();
+ private PartitionedRegionStats getPartitionedRegionStats() {
+ return regionAdvisor.getPartitionedRegionStats();
}
/**
@@ -413,13 +405,13 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*/
@Override
protected void profileCreated(Profile profile) {
- this.regionAdvisor.incrementBucketCount(profile);
+ regionAdvisor.incrementBucketCount(profile);
super.profileCreated(profile);
if (updateRedundancy() > 0) {
// wake up any threads in waitForRedundancy or waitForPrimary
- this.notifyAll();
+ notifyAll();
}
- this.regionAdvisor.updateBucketStatus(this.getBucket().getId(), profile.peerMemberId, false);
+ regionAdvisor.updateBucketStatus(getBucket().getId(), profile.peerMemberId, false);
if (logger.isDebugEnabled()) {
logger.debug("Profile added {} Profile : {}", getBucket().getFullPath(), profile);
}
@@ -436,9 +428,9 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
super.profileUpdated(profile);
if (updateRedundancy() > 0) {
// wake up any threads in waitForRedundancy or waitForPrimary
- this.notifyAll();
+ notifyAll();
}
- this.regionAdvisor.updateBucketStatus(this.getBucket().getId(), profile.peerMemberId, false);
+ regionAdvisor.updateBucketStatus(getBucket().getId(), profile.peerMemberId, false);
if (logger.isDebugEnabled()) {
logger.debug("Profile updated {} Profile : {}", getBucket().getFullPath(), profile);
@@ -454,15 +446,15 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
@Override
protected void profileRemoved(Profile profile) {
if (profile != null) {
- this.regionAdvisor.updateBucketStatus(this.getBucket().getId(),
+ regionAdvisor.updateBucketStatus(getBucket().getId(),
profile.getDistributedMember(), true);
- this.regionAdvisor.decrementsBucketCount(profile);
+ regionAdvisor.decrementsBucketCount(profile);
}
updateRedundancy();
if (logger.isDebugEnabled()) {
logger.debug("Profile removed {} the member lost {} Profile : {}", getBucket().getFullPath(),
- profile.getDistributedMember(), profile);
+ profile != null ? profile.getDistributedMember() : null, profile);
}
synchronized (this) {
updateServerBucketProfile();
@@ -497,21 +489,17 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
public void checkForLostPrimaryElector(Profile profile) {
// If the member that went away was in the middle of creating
// the bucket, finish the bucket creation.
- ProfileId elector = this.primaryElector;
+ ProfileId elector = primaryElector;
if (elector != null && elector.equals(profile.getDistributedMember())) {
if (logger.isDebugEnabled()) {
logger.debug(
"Bucket {} lost the member responsible for electing the primary. Finishing bucket creation",
getBucket().getFullPath());
}
- this.primaryElector = getBucket().getDistributionManager().getId();
- this.getBucket().getDistributionManager().getWaitingThreadPool().execute(new Runnable() {
- @Override
- public void run() {
- getBucket().getPartitionedRegion().getRedundancyProvider()
- .finishIncompleteBucketCreation(getBucket().getId());
- }
- });
+ primaryElector = getBucket().getDistributionManager().getId();
+ getBucket().getDistributionManager().getWaitingThreadPool().execute(
+ () -> getBucket().getPartitionedRegion().getRedundancyProvider()
+ .finishIncompleteBucketCreation(getBucket().getId()));
}
}
@@ -572,11 +560,12 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
private static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
if (map.isEmpty()) {
- return new SetFromMap<E>(map);
+ return new SetFromMap<>(map);
}
throw new IllegalArgumentException();
}
+ @SuppressWarnings("NullableProblems")
private static class SetFromMap<E> extends AbstractSet<E> implements Serializable {
private static final long serialVersionUID = 2454657854757543876L;
@@ -661,10 +650,9 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
return m.size();
}
- @SuppressWarnings("unchecked")
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
- backingSet = m == null ? Collections.<E>emptySet() : m.keySet();
+ backingSet = m == null ? Collections.emptySet() : m.keySet();
}
}
@@ -672,15 +660,15 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* repopulates the RegionAdvisor's location information for this bucket
*/
private void updateServerBucketProfile() {
- int bucketId = this.getBucket().getId();
+ int bucketId = getBucket().getId();
Set<ServerBucketProfile> serverProfiles =
- newSetFromMap(new HashMap<ServerBucketProfile, Boolean>());
- for (Profile p : this.profiles) {
+ newSetFromMap(new HashMap<>());
+ for (Profile p : profiles) {
if (p instanceof ServerBucketProfile) {
serverProfiles.add((ServerBucketProfile) p);
}
}
- this.regionAdvisor.setClientBucketProfiles(bucketId, serverProfiles);
+ regionAdvisor.setClientBucketProfiles(bucketId, serverProfiles);
}
/**
@@ -688,11 +676,11 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*
*/
public synchronized void updateServerBucketProfile(BucketProfile p) {
- this.localProfile = p;
+ localProfile = p;
}
public BucketProfile getLocalProfile() {
- return this.localProfile;
+ return localProfile;
}
@Override
@@ -731,18 +719,18 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
}
@Override
- public Set adviseProfileExchange() {
+ public Set<InternalDistributedMember> adviseProfileExchange() {
// delegate up to RegionAdvisor to include members that might have
// ProxyBucketRegion without a real BucketRegion
- Assert.assertTrue(this.regionAdvisor.isInitialized());
- return this.regionAdvisor.adviseBucketProfileExchange();
+ Assert.assertTrue(regionAdvisor.isInitialized());
+ return regionAdvisor.adviseBucketProfileExchange();
}
@Override
- public Set adviseProfileUpdate() {
+ public Set<InternalDistributedMember> adviseProfileUpdate() {
// delegate up to RegionAdvisor to include members that might have
// ProxyBucketRegion without a real BucketRegion
- return this.regionAdvisor.adviseGeneric();
+ return regionAdvisor.adviseGeneric();
}
/**
@@ -791,22 +779,6 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
}
/**
- * If the current member is primary for this bucket return true, otherwise, give some time for the
- * current member to become primary and then return whether it is a primary (true/false).
- */
- public boolean isPrimaryWithWait() {
- if (this.isPrimary()) {
- return true;
- }
- // wait for the current member to become primary holder
- InternalDistributedMember primary = waitForNewPrimary();
- if (primary != null) {
- return true;
- }
- return false;
- }
-
- /**
* This method was split out from getPrimary() due to bug #40639 and is only intended to be called
* from within that method.
*
@@ -814,15 +786,14 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* @return the new primary
*/
private InternalDistributedMember waitForNewPrimary() {
- DistributionManager dm = this.regionAdvisor.getDistributionManager();
+ DistributionManager dm = regionAdvisor.getDistributionManager();
DistributionConfig config = dm.getConfig();
// failure detection period
long timeout = config.getMemberTimeout() * 3L;
// plus time for a new member to become primary
timeout += Long.getLong(DistributionConfig.GEMFIRE_PREFIX + "BucketAdvisor.getPrimaryTimeout",
15000L);
- InternalDistributedMember newPrimary = waitForPrimaryMember(timeout);
- return newPrimary;
+ return waitForPrimaryMember(timeout);
}
/**
@@ -845,7 +816,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*
* @param member the member who is not primary
*/
- public void removePrimary(InternalDistributedMember member) {
+ private void removePrimary(InternalDistributedMember member) {
boolean needToVolunteerForPrimary = false;
if (!isClosed()) { // hole: requestPrimaryState not hosting
initializationGate();
@@ -853,14 +824,13 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
boolean lostPrimary = false;
try {
synchronized (this) {
- boolean wasPrimary = isPrimary() && this.getDistributionManager().getId().equals(member);
- final InternalDistributedMember currentPrimary =
- (InternalDistributedMember) this.primaryMember.get();
+ boolean wasPrimary = isPrimary() && getDistributionManager().getId().equals(member);
+ final InternalDistributedMember currentPrimary = primaryMember.get();
if (currentPrimary != null && currentPrimary.equals(member)) {
if (logger.isDebugEnabled()) {
logger.debug("[BucketAdvisor.notPrimary] {} for {}", member, this);
}
- this.primaryMember.set(null);
+ primaryMember.set(null);
} else {
return;
}
@@ -872,14 +842,10 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// member is primary... need to change state to NO_PRIMARY_xxx
if (isHosting()) {
requestPrimaryState(NO_PRIMARY_HOSTING);
- if (this.pRegion.isFixedPartitionedRegion()) {
+ if (pRegion.isFixedPartitionedRegion()) {
InternalDistributedMember primaryMember =
- this.regionAdvisor.adviseFixedPrimaryPartitionDataStore(this.getBucket().getId());
- if (primaryMember == null || primaryMember.equals(member)) {
- needToVolunteerForPrimary = true;
- } else {
- needToVolunteerForPrimary = false;
- }
+ regionAdvisor.adviseFixedPrimaryPartitionDataStore(getBucket().getId());
+ needToVolunteerForPrimary = primaryMember == null || primaryMember.equals(member);
} else {
needToVolunteerForPrimary = true;
}
@@ -896,15 +862,15 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
} finally {
if (lostPrimary) {
invokeAfterSecondaryInPartitionListeners();
- Bucket br = this.regionAdvisor.getBucket(getBucket().getId());
- if (br != null && br instanceof BucketRegion) {
+ Bucket br = regionAdvisor.getBucket(getBucket().getId());
+ if (br instanceof BucketRegion) {
((BucketRegion) br).beforeReleasingPrimaryLockDuringDemotion();
}
releasePrimaryLock();
// this was a deposePrimary call so we need to depose children as well
deposePrimaryForColocatedChildren();
- if (this.pRegion.isFixedPartitionedRegion()) {
+ if (pRegion.isFixedPartitionedRegion()) {
deposeOtherPrimaryBucketForFixedPartition();
}
}
@@ -928,7 +894,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* Actually close this advisor for real. Called by ProxyBucketRegion only. Calling this method
* actually closes this advisor whereas {@link #close()} only sets hosting to false.
*/
- protected void closeAdvisor() {
+ void closeAdvisor() {
boolean wasPrimary;
synchronized (this) {
if (isClosed()) {
@@ -936,9 +902,9 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
}
wasPrimary = isPrimary();
super.close();
- this.requestPrimaryState(CLOSED);
- this.redundancyTracker.closeBucket();
- this.localProfile = null;
+ requestPrimaryState(CLOSED);
+ redundancyTracker.closeBucket();
+ localProfile = null;
}
if (wasPrimary) {
releasePrimaryLock();
@@ -952,7 +918,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*/
protected boolean isClosed() {
synchronized (this) {
- return this.primaryState == CLOSED;
+ return primaryState == CLOSED;
}
}
@@ -963,7 +929,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*/
public boolean isPrimary() {
synchronized (this) {
- return this.primaryState == IS_PRIMARY_HOSTING;
+ return primaryState == IS_PRIMARY_HOSTING;
}
}
@@ -972,9 +938,9 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*
* @return true if this member is currently volunteering for primary
*/
- protected boolean isVolunteering() {
+ private boolean isVolunteering() {
synchronized (this) {
- return this.primaryState == VOLUNTEERING_HOSTING;
+ return primaryState == VOLUNTEERING_HOSTING;
}
}
@@ -983,10 +949,10 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*
* @return true if this member is currently attempting to become primary
*/
- protected boolean isBecomingPrimary() {
+ private boolean isBecomingPrimary() {
synchronized (this) {
- return this.primaryState == BECOMING_HOSTING && this.volunteeringDelegate != null
- && this.volunteeringDelegate.isAggressive();
+ return primaryState == BECOMING_HOSTING && volunteeringDelegate != null
+ && volunteeringDelegate.isAggressive();
}
}
@@ -997,9 +963,9 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*/
public boolean isHosting() {
synchronized (this) {
- return this.primaryState == NO_PRIMARY_HOSTING || this.primaryState == OTHER_PRIMARY_HOSTING
- || this.primaryState == VOLUNTEERING_HOSTING || this.primaryState == BECOMING_HOSTING
- || this.primaryState == IS_PRIMARY_HOSTING;
+ return primaryState == NO_PRIMARY_HOSTING || primaryState == OTHER_PRIMARY_HOSTING
+ || primaryState == VOLUNTEERING_HOSTING || primaryState == BECOMING_HOSTING
+ || primaryState == IS_PRIMARY_HOSTING;
}
}
@@ -1024,16 +990,16 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
return;
}
- if (this.volunteeringDelegate == null) {
+ if (volunteeringDelegate == null) {
setVolunteeringDelegate(new VolunteeringDelegate());
}
- this.volunteeringDelegate.volunteerForPrimary();
+ volunteeringDelegate.volunteerForPrimary();
}
}
protected void setVolunteeringDelegate(VolunteeringDelegate delegate) {
- this.volunteeringDelegate = delegate;
+ volunteeringDelegate = delegate;
}
/**
@@ -1049,7 +1015,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
try {
long waitTime = 2000; // time each iteration will wait
while (!isPrimary()) {
- this.getAdvisee().getCancelCriterion().checkCancelInProgress(null);
+ getAdvisee().getCancelCriterion().checkCancelInProgress(null);
boolean attemptToBecomePrimary = false;
boolean attemptToDeposePrimary = false;
@@ -1074,7 +1040,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
if (logger.isDebugEnabled()) {
logger.debug("Waiting for volunteering thread {}. Time left: {} ms", this, waitTime);
}
- this.wait(waitTime); // spurious wakeup ok
+ wait(waitTime); // spurious wakeup ok
continue;
} else if (isBecomingPrimary()) {
@@ -1083,10 +1049,10 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
} else {
// invoke becomePrimary AFTER sync is released in this thread...
- vDelegate = this.volunteeringDelegate;
+ vDelegate = volunteeringDelegate;
if (vDelegate == null) {
vDelegate = new VolunteeringDelegate();
- this.volunteeringDelegate = vDelegate;
+ volunteeringDelegate = vDelegate;
}
} // else
} // synchronized
@@ -1100,10 +1066,10 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// release synchronization and then call becomePrimary
if (attemptToBecomePrimary) {
synchronized (this) {
- if (this.volunteeringDelegate == null) {
- this.volunteeringDelegate = new VolunteeringDelegate();
+ if (volunteeringDelegate == null) {
+ volunteeringDelegate = new VolunteeringDelegate();
}
- this.volunteeringDelegate.volunteerForPrimary();
+ volunteeringDelegate.volunteerForPrimary();
attemptToDeposePrimary = true;
} // synchronized
Thread.sleep(10);
@@ -1118,7 +1084,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
logger.debug("Attempting to depose primary on {} for {}", otherPrimary, this);
}
DeposePrimaryBucketResponse response =
- DeposePrimaryBucketMessage.send(otherPrimary, this.pRegion, getBucket().getId());
+ DeposePrimaryBucketMessage.send(otherPrimary, pRegion, getBucket().getId());
if (response != null) {
response.waitForRepliesUninterruptibly();
if (logger.isDebugEnabled()) {
@@ -1149,7 +1115,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* @return the member or null if no primary exists
*/
public InternalDistributedMember basicGetPrimaryMember() {
- return (InternalDistributedMember) this.primaryMember.get();
+ return primaryMember.get();
}
/**
@@ -1157,7 +1123,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*
* @return true if successfully changed state to IS_PRIMARY
*/
- protected boolean acquiredPrimaryLock() {
+ private boolean acquiredPrimaryLock() {
if (logger.isDebugEnabled()) {
logger.debug("Acquired primary lock for BucketID {} PR : {}", getBucket().getId(),
regionAdvisor.getPartitionedRegion().getFullPath());
@@ -1172,8 +1138,8 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
try {
synchronized (this) {
if (isHosting() && (isVolunteering() || isBecomingPrimary())) {
- Bucket br = this.regionAdvisor.getBucket(getBucket().getId());
- if (br != null && br instanceof BucketRegion) {
+ Bucket br = regionAdvisor.getBucket(getBucket().getId());
+ if (br instanceof BucketRegion) {
((BucketRegion) br).beforeAcquiringPrimaryState();
}
if (requestPrimaryState(IS_PRIMARY_HOSTING)) {
@@ -1200,8 +1166,8 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// send profile update AFTER releasing sync
sendProfileUpdate();
- Bucket br = this.regionAdvisor.getBucket(getBucket().getId());
- if (br != null && br instanceof BucketRegion) {
+ Bucket br = regionAdvisor.getBucket(getBucket().getId());
+ if (br instanceof BucketRegion) {
((BucketRegion) br).processPendingSecondaryExpires();
}
if (br instanceof BucketRegionQueue) { // Shouldn't it be AbstractBucketRegionQueue
@@ -1209,7 +1175,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
brq.incQueueSize(brq.size());
brq.decSecondaryQueueSize(brq.size());
}
- if (br != null && br instanceof BucketRegion) {
+ if (br instanceof BucketRegion) {
((BucketRegion) br).afterAcquiringPrimaryState();
}
} else {
@@ -1223,12 +1189,11 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
}
private void invokePartitionListeners() {
- PartitionListener[] listeners = this.pRegion.getPartitionListeners();
+ PartitionListener[] listeners = pRegion.getPartitionListeners();
if (listeners == null || listeners.length == 0) {
return;
}
- for (int i = 0; i < listeners.length; i++) {
- PartitionListener listener = listeners[i];
+ for (PartitionListener listener : listeners) {
if (listener != null) {
listener.afterPrimary(getBucket().getId());
}
@@ -1236,12 +1201,11 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
}
private void invokeAfterSecondaryInPartitionListeners() {
- PartitionListener[] listeners = this.pRegion.getPartitionListeners();
+ PartitionListener[] listeners = pRegion.getPartitionListeners();
if (listeners == null || listeners.length == 0) {
return;
}
- for (int i = 0; i < listeners.length; i++) {
- PartitionListener listener = listeners[i];
+ for (PartitionListener listener : listeners) {
if (listener != null) {
listener.afterSecondary(getBucket().getId());
}
@@ -1256,9 +1220,9 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* @param createDLS true will create DLS if it does not exist
* @return distributed lock indicating primary member or null
*/
- DistributedMemberLock getPrimaryLock(boolean createDLS) {
+ private DistributedMemberLock getPrimaryLock(boolean createDLS) {
synchronized (this) {
- if (this.primaryLock == null) {
+ if (primaryLock == null) {
DistributedLockService dls = DistributedLockService
.getServiceNamed(PartitionedRegionHelper.PARTITION_LOCK_SERVICE_NAME);
if (dls == null) {
@@ -1281,23 +1245,21 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// TODO: we need a good NotConnectedException to replace
// IllegalStateException and ShutdownException
// perhaps: DistributedSystemUnavailableException
- catch (IllegalStateException e) {
+ catch (IllegalStateException | DistributedSystemDisconnectedException e) {
// create still throws IllegalStateException if isDisconnecting is true
return null;
- } catch (DistributedSystemDisconnectedException e) {
- // this would certainly prevent us from creating a DLS... messy
- return null;
- }
+ } // this would certainly prevent us from creating a DLS... messy
+
}
- this.primaryLock = new DistributedMemberLock(dls, getAdvisee().getName(),
+ primaryLock = new DistributedMemberLock(dls, getAdvisee().getName(),
DistributedMemberLock.NON_EXPIRING_LEASE,
DistributedMemberLock.LockReentryPolicy.PREVENT_SILENTLY);
}
- return this.primaryLock;
+ return primaryLock;
}
}
- protected void acquirePrimaryRecursivelyForColocated() {
+ private void acquirePrimaryRecursivelyForColocated() {
final List<PartitionedRegion> colocatedWithList =
ColocationHelper.getColocatedChildRegions(regionAdvisor.getPartitionedRegion());
if (colocatedWithList != null) {
@@ -1320,7 +1282,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
childBA.setVolunteering();
boolean acquired = childBA.acquiredPrimaryLock();
acquireForChild = true;
- if (acquired && this.pRegion.isFixedPartitionedRegion()) {
+ if (acquired && pRegion.isFixedPartitionedRegion()) {
childBA.acquirePrimaryForRestOfTheBucket();
}
} else {
@@ -1338,8 +1300,8 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
}
}
- protected void acquirePrimaryForRestOfTheBucket() {
- List<FixedPartitionAttributesImpl> fpas = this.pRegion.getFixedPartitionAttributesImpl();
+ private void acquirePrimaryForRestOfTheBucket() {
+ List<FixedPartitionAttributesImpl> fpas = pRegion.getFixedPartitionAttributesImpl();
if (fpas != null) {
int bucketId = getBucket().getId();
for (FixedPartitionAttributesImpl fpa : fpas) {
@@ -1361,8 +1323,6 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
}
}
}
- } else {
- continue;
}
}
}
@@ -1372,7 +1332,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* Sets volunteering to true. Returns true if the state of volunteering was changed. Returns false
* if voluntering was already equal to true. Caller should do nothing if false is returned.
*/
- protected boolean setVolunteering() {
+ private boolean setVolunteering() {
synchronized (this) {
return requestPrimaryState(VOLUNTEERING_HOSTING);
}
@@ -1382,7 +1342,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* Sets becoming primary to true. Returns true if the state of becoming was changed. Returns false
* if becoming was already equal to true. Caller should do nothing if false is returned.
*/
- protected boolean setBecoming() {
+ private boolean setBecoming() {
synchronized (this) {
return requestPrimaryState(BECOMING_HOSTING);
}
@@ -1394,7 +1354,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* @param timeout time in milliseconds to wait for a primary
* @return the primary bucket host
*/
- protected InternalDistributedMember waitForPrimaryMember(long timeout) {
+ private InternalDistributedMember waitForPrimaryMember(long timeout) {
synchronized (this) {
// let's park this thread and wait for a primary!
StopWatch timer = new StopWatch(true);
@@ -1403,7 +1363,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
try {
for (;;) {
// bail out if the system starts closing
- this.getAdvisee().getCancelCriterion().checkCancelInProgress(null);
+ getAdvisee().getCancelCriterion().checkCancelInProgress(null);
final InternalCache cache = getBucket().getCache();
if (cache != null && cache.isCacheAtShutdownAll()) {
throw cache.getCacheClosedException("Cache is shutting down");
@@ -1441,14 +1401,14 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
logger
.warn(
"{} secs have elapsed waiting for a primary for bucket {}. Current bucket owners {}",
- new Object[] {warnTime / 1000L, this, this.adviseInitialized()});
+ new Object[] {warnTime / 1000L, this, adviseInitialized()});
// log a warning;
loggedWarning = true;
} else {
timeLeft = timeLeft > timeUntilWarning ? timeUntilWarning : timeLeft;
}
}
- this.wait(timeLeft); // spurious wakeup ok
+ wait(timeLeft); // spurious wakeup ok
}
} catch (InterruptedException e) {
// abort and return null
@@ -1494,41 +1454,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
if (logger.isDebugEnabled()) {
logger.debug("Waiting for bucket {}", this);
}
- this.wait(timeLeft); // spurious wakeup ok
- }
- } catch (InterruptedException e) {
- // abort and return null
- Thread.currentThread().interrupt();
- }
- return false;
- }
- }
-
- private static final long BUCKET_STORAGE_WAIT =
- Long.getLong(DistributionConfig.GEMFIRE_PREFIX + "BUCKET_STORAGE_WAIT", 15000).longValue(); // 15
- // seconds
-
- public boolean waitForStorage() {
- synchronized (this) {
- // let's park this thread and wait for storage!
- StopWatch timer = new StopWatch(true);
- try {
- for (;;) {
- if (this.regionAdvisor.isBucketLocal(getBucket().getId())) {
- return true;
- }
- getProxyBucketRegion().getPartitionedRegion().checkReadiness();
- if (isClosed()) {
- return false;
- }
- long timeLeft = BUCKET_STORAGE_WAIT - timer.elapsedTimeMillis();
- if (timeLeft <= 0) {
- return false;
- }
- if (logger.isDebugEnabled()) {
- logger.debug("Waiting for bucket storage" + this);
- }
- this.wait(timeLeft); // spurious wakeup ok
+ wait(timeLeft); // spurious wakeup ok
}
} catch (InterruptedException e) {
// abort and return null
@@ -1538,19 +1464,19 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
}
}
- public synchronized void clearPrimaryElector() {
+ synchronized void clearPrimaryElector() {
primaryElector = null;
}
- public synchronized void setPrimaryElector(InternalDistributedMember newPrimaryElector) {
+ synchronized void setPrimaryElector(InternalDistributedMember newPrimaryElector) {
// Only set the new primary elector if we have not yet seen
// a primary for this bucket.
- if (this.primaryElector != null) {
+ if (primaryElector != null) {
if (newPrimaryElector != null && !regionAdvisor.hasPartitionedRegion(newPrimaryElector)) {
// no longer a participant - don't use it
- this.primaryElector = null;
+ primaryElector = null;
} else {
- this.primaryElector = newPrimaryElector;
+ primaryElector = newPrimaryElector;
}
}
}
@@ -1563,9 +1489,9 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
if (parentAdvisor == null) {
if (newPrimaryElector != null && !regionAdvisor.hasPartitionedRegion(newPrimaryElector)) {
// no longer a participant - don't use it
- this.primaryElector = null;
+ primaryElector = null;
} else {
- this.primaryElector = newPrimaryElector;
+ primaryElector = newPrimaryElector;
}
}
}
@@ -1578,7 +1504,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
protected void setHosting(boolean value) {
// boolean needToNotPrimarySelf = false;
boolean needToVolunteerForPrimary = false;
- boolean wasPrimary = false;
+ boolean wasPrimary;
synchronized (this) {
wasPrimary = isPrimary();
if (isClosed()) {
@@ -1597,7 +1523,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
if (hasPrimary()) { // has primary...
if (isPrimary()) {
requestPrimaryState(NO_PRIMARY_NOT_HOSTING);
- this.primaryMember.set(null);
+ primaryMember.set(null);
findAndSetPrimaryMember();
} else {
requestPrimaryState(OTHER_PRIMARY_NOT_HOSTING);
@@ -1607,14 +1533,14 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
requestPrimaryState(NO_PRIMARY_NOT_HOSTING);
}
}
- this.volunteeringDelegate = null;
+ volunteeringDelegate = null;
// Note - checkRedundancy has the side effect that it updates the stats.
// We need to invoke checkRedundancy here, regardless of whether we
// need this notify.
if (updateRedundancy() > 0 && isHosting()) {
// wake up any threads in waitForRedundancy or waitForPrimary
- this.notifyAll();
+ notifyAll();
}
}
if (wasPrimary) {
@@ -1642,7 +1568,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* distributed deadlocks.
*/
private void sendProfileUpdate() {
- if (this.getDistributionManager().getSystem().isLoner()) {
+ if (getDistributionManager().getSystem().isLoner()) {
// no one to send the profile update... return to prevent bug 39760
return;
}
@@ -1651,13 +1577,13 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
"Attempting to sendProfileUpdate while synchronized may result in deadlock");
// NOTE: if this assert fails, you COULD use the WaitingThreadPool in DM
- final int partitionedRegionId = this.pRegion.getPRId();
+ final int partitionedRegionId = pRegion.getPRId();
final int bucketId = ((ProxyBucketRegion) getAdvisee()).getBucketId();
BucketProfile bp = (BucketProfile) createProfile();
updateServerBucketProfile(bp);
InternalDistributedMember primary = basicGetPrimaryMember();
- HashSet hostsAndProxyMembers = new HashSet();
+ HashSet<InternalDistributedMember> hostsAndProxyMembers = new HashSet<>();
if (primary != null && !primary.equals(getDistributionManager().getId())) {
hostsAndProxyMembers.add(primary); // Add the primary
}
@@ -1676,25 +1602,24 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*/
private boolean hasPrimary() {
synchronized (this) {
- return this.primaryState == OTHER_PRIMARY_NOT_HOSTING
- || this.primaryState == OTHER_PRIMARY_HOSTING || this.primaryState == IS_PRIMARY_HOSTING;
+ return primaryState == OTHER_PRIMARY_NOT_HOSTING
+ || primaryState == OTHER_PRIMARY_HOSTING || primaryState == IS_PRIMARY_HOSTING;
}
}
@Override
protected Profile instantiateProfile(InternalDistributedMember memberId, int version) {
- if (!this.pRegion.isShadowPR()) {
+ if (!pRegion.isShadowPR()) {
InternalCache cache = getProxyBucketRegion().getCache();
- List servers = null;
- servers = cache.getCacheServers();
+ List<CacheServer> servers = cache.getCacheServers();
- HashSet<BucketServerLocation66> serverLocations = new HashSet<BucketServerLocation66>();
- for (Object object : servers) {
- CacheServerImpl server = (CacheServerImpl) object;
+ HashSet<BucketServerLocation66> serverLocations = new HashSet<>();
+ for (CacheServer cacheServer : servers) {
+ CacheServerImpl server = (CacheServerImpl) cacheServer;
if (server.isRunning() && (server.getExternalAddress() != null)) {
BucketServerLocation66 location = new BucketServerLocation66(getBucket().getId(),
- server.getPort(), server.getExternalAddress()
- /* .getExternalAddress(false/ checkServerRunning ) */, getBucket().isPrimary(), Integer.valueOf(version).byteValue(), server.getCombinedGroups());
+ server.getPort(), server.getExternalAddress(), getBucket().isPrimary(),
+ Integer.valueOf(version).byteValue(), server.getCombinedGroups());
serverLocations.add(location);
}
}
@@ -1710,7 +1635,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*
* @param id the member to use as primary for this bucket
*/
- void setPrimaryMember(InternalDistributedMember id) {
+ private void setPrimaryMember(InternalDistributedMember id) {
if (!getDistributionManager().getId().equals(id)) {
// volunteerForPrimary handles primary state change if its our id
if (isHosting()) {
@@ -1719,21 +1644,21 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
requestPrimaryState(OTHER_PRIMARY_NOT_HOSTING);
}
}
- this.primaryMember.set(id);
- this.everHadPrimary = true;
+ primaryMember.set(id);
+ everHadPrimary = true;
if (id != null && id.equals(primaryElector)) {
primaryElector = null;
}
- this.notifyAll(); // wake up any threads in waitForPrimaryMember
+ notifyAll(); // wake up any threads in waitForPrimaryMember
}
- public void setHadPrimary() {
- this.everHadPrimary = true;
+ void setHadPrimary() {
+ everHadPrimary = true;
}
- public boolean getHadPrimary() {
- return this.everHadPrimary;
+ boolean getHadPrimary() {
+ return everHadPrimary;
}
public InternalDistributedMember getPrimaryElector() {
@@ -1765,20 +1690,16 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* @return zero or greater array of primary members
*/
private InternalDistributedMember[] findPrimaryMembers() {
- Set primaryMembers = adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof BucketProfile;
- BucketProfile srp = (BucketProfile) profile;
- return srp.isPrimary;
- }
+ Set<InternalDistributedMember> primaryMembers = adviseFilter(profile -> {
+ assert profile instanceof BucketProfile;
+ BucketProfile srp = (BucketProfile) profile;
+ return srp.isPrimary;
});
if (primaryMembers.size() > 1 && logger.isDebugEnabled()) {
logger.debug("[findPrimaryProfiles] found the following primary members for {}: {}",
getAdvisee().getName(), primaryMembers);
}
- return (InternalDistributedMember[]) primaryMembers
- .toArray(new InternalDistributedMember[primaryMembers.size()]);
+ return primaryMembers.toArray(new InternalDistributedMember[0]);
}
/**
@@ -1788,9 +1709,9 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* @return true if a primary member was found and used
* @see #findAndSetPrimaryMember()
*/
- boolean findAndSetPrimaryMember() {
+ private boolean findAndSetPrimaryMember() {
if (isPrimary()) {
- setPrimaryMember(this.getDistributionManager().getDistributionManagerId());
+ setPrimaryMember(getDistributionManager().getDistributionManagerId());
return true;
}
InternalDistributedMember[] primaryMembers = findPrimaryMembers();
@@ -1812,19 +1733,16 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
return redundancyTracker.getCurrentRedundancy();
}
- public Set<InternalDistributedMember> adviseInitialized() {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof BucketProfile;
- BucketProfile bucketProfile = (BucketProfile) profile;
- return bucketProfile.isHosting;
- }
+ Set<InternalDistributedMember> adviseInitialized() {
+ return adviseFilter(profile -> {
+ assert profile instanceof BucketProfile;
+ BucketProfile bucketProfile = (BucketProfile) profile;
+ return bucketProfile.isHosting;
});
}
- public Set<InternalDistributedMember> adviseRecoveredFromDisk() {
+ Set<InternalDistributedMember> adviseRecoveredFromDisk() {
return regionAdvisor.adviseInitializedDataStore();
}
@@ -1835,7 +1753,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* bucket. If it is used more frequently, it might be better to cache this count.
*/
private int getNumInitializedBuckets() {
- Profile[] locProfiles = this.profiles; // grab current profiles
+ Profile[] locProfiles = profiles; // grab current profiles
int count = 0;
for (Profile profile : locProfiles) {
BucketProfile bucketProfile = (BucketProfile) profile;
@@ -1856,7 +1774,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
/**
* Releases the primary lock for this bucket.
*/
- protected void releasePrimaryLock() {
+ private void releasePrimaryLock() {
// We don't have a lock if we have a parent advisor
if (parentAdvisor != null) {
return;
@@ -1879,7 +1797,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
}
private String primaryStateToString() {
- return primaryStateToString(this.primaryState);
+ return primaryStateToString(primaryState);
}
/**
@@ -1920,7 +1838,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* @throws IllegalStateException if an illegal state change was attempted
*/
private boolean requestPrimaryState(byte requestedState) {
- final byte fromState = this.primaryState;
+ final byte fromState = primaryState;
switch (fromState) {
case NO_PRIMARY_NOT_HOSTING:
switch (requestedState) {
@@ -1928,13 +1846,13 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// race condition ok, return false
return false;
case NO_PRIMARY_HOSTING:
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
case OTHER_PRIMARY_NOT_HOSTING:
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
case OTHER_PRIMARY_HOSTING:
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
case BECOMING_HOSTING:
// race condition during close is ok, return false
@@ -1943,18 +1861,17 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// race condition during close is ok, return false
return false;
case CLOSED:
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
default:
throw new IllegalStateException(String.format("Cannot change from %s to %s",
- new Object[] {this.primaryStateToString(),
- this.primaryStateToString(requestedState)}));
+ primaryStateToString(), primaryStateToString(requestedState)));
}
break;
case NO_PRIMARY_HOSTING:
switch (requestedState) {
case NO_PRIMARY_NOT_HOSTING:
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
// case OTHER_PRIMARY_NOT_HOSTING: -- enable for bucket migration
// this.primaryState = requestedState;
@@ -1963,39 +1880,39 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// race condition ok, return false
return false;
case VOLUNTEERING_HOSTING:
- this.primaryState = requestedState; {
+ primaryState = requestedState; {
PartitionedRegionStats stats = getPartitionedRegionStats();
stats.putStartTime(this, stats.startVolunteering());
}
break;
case BECOMING_HOSTING:
- this.primaryState = requestedState; {
+ primaryState = requestedState; {
PartitionedRegionStats stats = getPartitionedRegionStats();
stats.putStartTime(this, stats.startVolunteering());
}
break;
case OTHER_PRIMARY_HOSTING:
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
case CLOSED:
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
default:
throw new IllegalStateException(String.format("Cannot change from %s to %s",
- new Object[] {this.primaryStateToString(),
- this.primaryStateToString(requestedState)}));
+ primaryStateToString(),
+ primaryStateToString(requestedState)));
}
break;
case OTHER_PRIMARY_NOT_HOSTING:
switch (requestedState) {
case NO_PRIMARY_NOT_HOSTING:
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
case OTHER_PRIMARY_NOT_HOSTING:
// race condition ok, return false
return false;
case OTHER_PRIMARY_HOSTING:
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
case BECOMING_HOSTING:
// race condition during close is ok, return false
@@ -2004,12 +1921,12 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// race condition during close is ok, return false
return false;
case CLOSED:
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
default:
throw new IllegalStateException(String.format("Cannot change from %s to %s",
- new Object[] {this.primaryStateToString(),
- this.primaryStateToString(requestedState)}));
+ primaryStateToString(),
+ primaryStateToString(requestedState)));
}
break;
case OTHER_PRIMARY_HOSTING:
@@ -2019,22 +1936,22 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// break;
case OTHER_PRIMARY_NOT_HOSTING:
// May occur when setHosting(false) is called
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
case OTHER_PRIMARY_HOSTING:
// race condition ok, return false
return false;
case NO_PRIMARY_HOSTING:
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
case CLOSED:
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
case VOLUNTEERING_HOSTING:
// race condition ok, return false to abort volunteering
return false;
case BECOMING_HOSTING:
- this.primaryState = requestedState; {
+ primaryState = requestedState; {
PartitionedRegionStats stats = getPartitionedRegionStats();
stats.putStartTime(this, stats.startVolunteering());
}
@@ -2043,19 +1960,19 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// race condition ok, probably race in HA where other becomes
// primary and immediately leaves while we have try-lock message
// enroute to grantor
- this.primaryState = requestedState;
+ primaryState = requestedState;
break;
default:
throw new IllegalStateException(String.format("Cannot change from %s to %s",
- new Object[] {this.primaryStateToString(),
- this.primaryStateToString(requestedState)}));
+ primaryStateToString(),
+ primaryStateToString(requestedState)));
}
break;
case VOLUNTEERING_HOSTING:
switch (requestedState) {
case NO_PRIMARY_NOT_HOSTING:
// May occur when setHosting(false) is called
- this.primaryState = requestedState; {
+ primaryState = requestedState; {
PartitionedRegionStats stats = getPartitionedRegionStats();
stats.endVolunteeringClosed(stats.removeStartTime(this));
}
@@ -2063,7 +1980,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
case OTHER_PRIMARY_NOT_HOSTING:
// May occur when setHosting(false) is called
// Profile update for other primary may have slipped in
- this.primaryState = requestedState; {
+ primaryState = requestedState; {
PartitionedRegionStats stats = getPartitionedRegionStats();
stats.endVolunteeringClosed(stats.removeStartTime(this));
}
@@ -2072,14 +1989,14 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// race condition occurred, return false and stay in volunteering
return false;
case IS_PRIMARY_HOSTING:
- this.primaryState = requestedState; {
+ primaryState = requestedState; {
PartitionedRegionStats stats = getPartitionedRegionStats();
stats.incPrimaryBucketCount(1);
stats.endVolunteeringBecamePrimary(stats.removeStartTime(this));
}
break;
case OTHER_PRIMARY_HOSTING:
- this.primaryState = requestedState; {
+ primaryState = requestedState; {
PartitionedRegionStats stats = getPartitionedRegionStats();
stats.endVolunteeringOtherPrimary(stats.removeStartTime(this));
}
@@ -2091,22 +2008,22 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// race condition ok, return false to abort volunteering
return false;
case CLOSED:
- this.primaryState = requestedState; {
+ primaryState = requestedState; {
PartitionedRegionStats stats = getPartitionedRegionStats();
stats.endVolunteeringClosed(stats.removeStartTime(this));
}
break;
default:
throw new IllegalStateException(String.format("Cannot change from %s to %s",
- new Object[] {this.primaryStateToString(),
- this.primaryStateToString(requestedState)}));
+ primaryStateToString(),
+ primaryStateToString(requestedState)));
}
break;
case BECOMING_HOSTING:
switch (requestedState) {
case NO_PRIMARY_NOT_HOSTING:
// May occur when setHosting(false) is called
- this.primaryState = requestedState; {
+ primaryState = requestedState; {
PartitionedRegionStats stats = getPartitionedRegionStats();
stats.endVolunteeringClosed(stats.removeStartTime(this));
}
@@ -2114,7 +2031,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
case OTHER_PRIMARY_NOT_HOSTING:
// May occur when setHosting(false) is called
// Profile update for other primary may have slipped in
- this.primaryState = requestedState; {
+ primaryState = requestedState; {
PartitionedRegionStats stats = getPartitionedRegionStats();
stats.endVolunteeringClosed(stats.removeStartTime(this));
}
@@ -2123,7 +2040,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// race condition occurred, return false and stay in volunteering
return false;
case IS_PRIMARY_HOSTING:
- this.primaryState = requestedState; {
+ primaryState = requestedState; {
PartitionedRegionStats stats = getPartitionedRegionStats();
stats.incPrimaryBucketCount(1);
stats.endVolunteeringBecamePrimary(stats.removeStartTime(this));
@@ -2138,15 +2055,15 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// race condition ok, return false to abort volunteering
return false;
case CLOSED:
- this.primaryState = requestedState; {
+ primaryState = requestedState; {
PartitionedRegionStats stats = getPartitionedRegionStats();
stats.endVolunteeringClosed(stats.removeStartTime(this));
}
break;
default:
throw new IllegalStateException(String.format("Cannot change from %s to %s",
- new Object[] {this.primaryStateToString(),
- this.primaryStateToString(requestedState)}));
+ primaryStateToString(),
+ primaryStateToString(requestedState)));
}
break;
case IS_PRIMARY_HOSTING:
@@ -2177,8 +2094,8 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
changeFromPrimaryTo(requestedState);
break;
default:
- throw new IllegalStateException("Cannot change from " + this.primaryStateToString()
- + " to " + this.primaryStateToString(requestedState));
+ throw new IllegalStateException("Cannot change from " + primaryStateToString()
+ + " to " + primaryStateToString(requestedState));
}
break;
case CLOSED:
@@ -2204,16 +2121,16 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
default:
throw new IllegalStateException(
String.format("Cannot change from %s to %s for bucket %s",
- new Object[] {this.primaryStateToString(),
- this.primaryStateToString(requestedState), getAdvisee().getName()}));
+ primaryStateToString(),
+ primaryStateToString(requestedState), getAdvisee().getName()));
}
}
- return this.primaryState == requestedState;
+ return primaryState == requestedState;
}
private void changeFromPrimaryTo(byte requestedState) {
try {
- this.primaryState = requestedState;
+ primaryState = requestedState;
} finally {
getPartitionedRegionStats().incPrimaryBucketCount(-1);
}
@@ -2223,7 +2140,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
public Set adviseDestroyRegion() {
// fix for bug 37604 - tell all owners of the pr that the bucket is being
// destroyed. This is needed when bucket cleanup is performed
- return this.regionAdvisor.adviseAllPRNodes();
+ return regionAdvisor.adviseAllPRNodes();
}
/**
@@ -2233,35 +2150,27 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* @return a set of recipients requiring both cache-op and notification messages
* @since GemFire 5.7
*/
- public Set adviseRequiresTwoMessages() {
+ public Set<InternalDistributedMember> adviseRequiresTwoMessages() {
return adviseNotInitialized();
}
- public Set adviseNotInitialized() {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- return !cp.regionInitialized;
- }
+ private Set<InternalDistributedMember> adviseNotInitialized() {
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile cp = (CacheProfile) profile;
+ return !cp.regionInitialized;
});
}
@Override
public Set adviseNetWrite() {
- return this.regionAdvisor.adviseNetWrite();
+ return regionAdvisor.adviseNetWrite();
}
@Override
public String toString() {
- // String identity = super.toString();
- // String identity = "BucketAdvisor " + getAdvisee().getFullPath() +
- // ":" + getAdvisee().getSerialNumber();
- // identity = identity.substring(identity.lastIndexOf(".")+1);
- // final StringBuffer sb = new StringBuffer("[" + identity + ": ");
final StringBuilder sb = new StringBuilder("[BucketAdvisor ").append(getAdvisee().getFullPath())
.append(':').append(getAdvisee().getSerialNumber()).append(": ");
sb.append("state=").append(primaryStateToString());
@@ -2286,7 +2195,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* Called from endBucket creation. We send out a profile to notify others that the persistence is
* initialized.
*/
- public void endBucketCreation() {
+ void endBucketCreation() {
sendProfileUpdate();
}
@@ -2315,8 +2224,8 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
public BucketProfile(InternalDistributedMember memberId, int version, Bucket bucket) {
super(memberId, version);
- this.isPrimary = bucket.isPrimary();
- this.isHosting = bucket.isHosting();
+ isPrimary = bucket.isPrimary();
+ isHosting = bucket.isHosting();
}
@Override
@@ -2327,25 +2236,25 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
@Override
public void fillInToString(StringBuilder sb) {
super.fillInToString(sb);
- sb.append("; isPrimary=" + this.isPrimary);
- sb.append("; isHosting=" + this.isHosting);
- sb.append("; isInitializing=" + this.isInitializing);
+ sb.append("; isPrimary=").append(isPrimary);
+ sb.append("; isHosting=").append(isHosting);
+ sb.append("; isInitializing=").append(isInitializing);
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
super.fromData(in);
- this.isPrimary = in.readBoolean();
- this.isHosting = in.readBoolean();
- this.isInitializing = in.readBoolean();
+ isPrimary = in.readBoolean();
+ isHosting = in.readBoolean();
+ isInitializing = in.readBoolean();
}
@Override
public void toData(DataOutput out) throws IOException {
super.toData(out);
- out.writeBoolean(this.isPrimary);
- out.writeBoolean(this.isHosting);
- out.writeBoolean(this.isInitializing);
+ out.writeBoolean(isPrimary);
+ out.writeBoolean(isHosting);
+ out.writeBoolean(isInitializing);
}
@Override
@@ -2367,8 +2276,8 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
public ServerBucketProfile(InternalDistributedMember memberId, int version, Bucket bucket,
HashSet<BucketServerLocation66> serverLocations) {
super(memberId, version, bucket);
- this.bucketId = bucket.getId();
- this.bucketServerLocations = serverLocations;
+ bucketId = bucket.getId();
+ bucketServerLocations = serverLocations;
}
@Override
@@ -2380,27 +2289,27 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
public void fillInToString(StringBuilder sb) {
super.fillInToString(sb);
for (BucketServerLocation66 location : bucketServerLocations) {
- sb.append("; hostName=" + location.getHostName());
- sb.append("; port=" + location.getPort());
+ sb.append("; hostName=").append(location.getHostName());
+ sb.append("; port=").append(location.getPort());
}
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
super.fromData(in);
- this.bucketServerLocations = SerializationHelper.readBucketServerLocationSet(in);
- this.bucketId = DataSerializer.readPrimitiveInt(in);
+ bucketServerLocations = SerializationHelper.readBucketServerLocationSet(in);
+ bucketId = DataSerializer.readPrimitiveInt(in);
}
@Override
public void toData(DataOutput out) throws IOException {
super.toData(out);
SerializationHelper.writeBucketServerLocationSet(bucketServerLocations, out);
- DataSerializer.writePrimitiveInt(this.bucketId, out);
+ DataSerializer.writePrimitiveInt(bucketId, out);
}
public Set<BucketServerLocation66> getBucketServerLocations() {
- return this.bucketServerLocations;
+ return bucketServerLocations;
}
@Override
@@ -2410,11 +2319,8 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
@Override
public int hashCode() {
- final int prime = 31;
- int result = 1;
BucketServerLocation66 sl = (BucketServerLocation66) bucketServerLocations.toArray()[0];
- result = prime * bucketId + sl.getPort();
- return result;
+ return 31 * bucketId + sl.getPort();
}
@Override
@@ -2426,16 +2332,13 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
if (!(obj instanceof ServerBucketProfile))
return false;
final ServerBucketProfile other = (ServerBucketProfile) obj;
- if (other.bucketId != this.bucketId) {
- return false;
- }
- if (other.bucketServerLocations.size() != this.bucketServerLocations.size()) {
+ if (other.bucketId != bucketId) {
return false;
}
- if (!other.bucketServerLocations.containsAll(this.bucketServerLocations)) {
+ if (other.bucketServerLocations.size() != bucketServerLocations.size()) {
return false;
}
- return true;
+ return other.bucketServerLocations.containsAll(bucketServerLocations);
}
}
@@ -2461,7 +2364,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*/
boolean isAggressive() {
synchronized (BucketAdvisor.this) {
- return this.aggressive;
+ return aggressive;
}
}
@@ -2475,12 +2378,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
getAdvisee().getCancelCriterion().checkCancelInProgress(null);
boolean interrupted = Thread.interrupted();
try {
- execute(new Runnable() {
- @Override
- public void run() {
- doVolunteerForPrimary();
- }
- });
+ execute(this::doVolunteerForPrimary);
handedOff = true;
} catch (InterruptedException e) {
interrupted = true;
@@ -2501,10 +2399,10 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
*/
boolean reserveForBecomePrimary() {
synchronized (BucketAdvisor.this) {
- if (this.volunteeringThread != null) {
+ if (volunteeringThread != null) {
return false;
}
- this.aggressive = true;
+ aggressive = true;
return true;
}
}
@@ -2530,9 +2428,9 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// operations from being performed on this primary until the child regions
// are synced up. It also prevents a depose from happening until then.
BucketAdvisor parentBA = parentAdvisor;
- BucketAdvisor.this.primaryMoveWriteLock.lock();
+ primaryMoveWriteLock.lock();
try {
- boolean acquiredLock = false;
+ boolean acquiredLock;
getAdvisee().getCancelCriterion().checkCancelInProgress(null);
// Check our parent advisor and set our state
// accordingly
@@ -2594,7 +2492,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
return;
}
} finally {
- BucketAdvisor.this.primaryMoveWriteLock.unlock();
+ primaryMoveWriteLock.unlock();
}
// else: acquiredPrimaryLock released thePrimaryLock
@@ -2608,9 +2506,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
} catch (LockServiceDestroyedException e) {
dlsDestroyed = true;
handleException(e, true);
- } catch (RegionDestroyedException e) {
- handleException(e, false);
- } catch (CancelException e) {
+ } catch (RegionDestroyedException | CancelException e) {
handleException(e, false);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
@@ -2651,14 +2547,14 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
private boolean beginVolunteering() {
synchronized (BucketAdvisor.this) {
- if (Thread.currentThread().equals(this.volunteeringThread)) {
+ if (Thread.currentThread().equals(volunteeringThread)) {
return true; // this thread is already volunteering or reserved
}
- if (this.volunteeringThread != null) {
+ if (volunteeringThread != null) {
// another thread is already volunteering
return false;
}
- this.volunteeringThread = Thread.currentThread();
+ volunteeringThread = Thread.currentThread();
boolean changedState = false;
try {
if (isAggressive()) {
@@ -2669,8 +2565,8 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
return changedState;
} finally {
if (!changedState) {
- this.aggressive = false;
- this.volunteeringThread = null;
+ aggressive = false;
+ volunteeringThread = null;
}
}
}
@@ -2679,7 +2575,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
private boolean continueVolunteering() {
synchronized (BucketAdvisor.this) {
// false if caller is not the volunteeringThread
- if (!Thread.currentThread().equals(this.volunteeringThread)) {
+ if (!Thread.currentThread().equals(volunteeringThread)) {
return false;
}
if (!isVolunteering() && !isBecomingPrimary()) {
@@ -2699,19 +2595,16 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
return false;
}
// false if no longer hosting
- if (!isHosting()) {
- return false;
- }
+ return isHosting();
// must be true... need to continue volunteering
- return true;
}
}
private void endVolunteering() {
- if (Thread.currentThread().equals(this.volunteeringThread)) {
- this.volunteeringThread = null;
- this.aggressive = false;
+ if (Thread.currentThread().equals(volunteeringThread)) {
+ volunteeringThread = null;
+ aggressive = false;
}
}
@@ -2741,7 +2634,7 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
// VOLUNTEERING_THREAD_COUNT.
if (Thread.interrupted())
throw new InterruptedException();
- Queue volunteeringQueue = getVolunteeringQueue();
+ Queue<Runnable> volunteeringQueue = getVolunteeringQueue();
synchronized (volunteeringQueue) {
// add the volunteering task
volunteeringQueue.add(volunteeringTask);
@@ -2767,59 +2660,55 @@ public class BucketAdvisor extends CacheDistributionAdvisor {
* @return runnable for consuming the volunteering queue
*/
private Runnable consumeQueue() {
- return new Runnable() {
- @Override
- public void run() {
- getPartitionedRegionStats().incVolunteeringThreads(1);
- boolean releaseSemaphore = true;
- try {
- Queue volunteeringQueue = getVolunteeringQueue();
- Runnable queuedWork = null;
- while (true) {
- // SystemFailure.checkFailure();
- getAdvisee().getCancelCriterion().checkCancelInProgress(null);
- synchronized (volunteeringQueue) {
- // synchronized volunteeringQueue for coordination between threads adding
- // work to the queue and checking for a consuming thread and the existing
- // consuming thread to determine if it can exit since the queue is empty.
- queuedWork = (Runnable) volunteeringQueue.poll();
- if (queuedWork == null) {
- // the queue is empty... no more work... so return
- // @todo why release the semaphore here are sync'ed?
- // we could just let the finally block do it.
- getVolunteeringSemaphore().release();
- releaseSemaphore = false;
- return;
- }
- // still more work in the queue so let's run it
- }
- try {
- queuedWork.run();
- } catch (CancelException e) {
+ return () -> {
+ getPartitionedRegionStats().incVolunteeringThreads(1);
+ boolean releaseSemaphore = true;
+ try {
+ Queue<Runnable> volunteeringQueue = getVolunteeringQueue();
+ Runnable queuedWork;
+ while (true) {
+ // SystemFailure.checkFailure();
+ getAdvisee().getCancelCriterion().checkCancelInProgress(null);
+ synchronized (volunteeringQueue) {
+ // synchronized volunteeringQueue for coordination between threads adding
+ // work to the queue and checking for a consuming thread and the existing
+ // consuming thread to determine if it can exit since the queue is empty.
+ queuedWork = volunteeringQueue.poll();
+ if (queuedWork == null) {
+ // the queue is empty... no more work... so return
+ // @todo why release the semaphore here are sync'ed?
+ // we could just let the finally block do it.
+ getVolunteeringSemaphore().release();
+ releaseSemaphore = false;
return;
- } catch (RuntimeException e) {
- // log and continue consuming queue
- logger.error(e.getMessage(), e);
}
+ // still more work in the queue so let's run it
}
- } finally {
- getPartitionedRegionStats().incVolunteeringThreads(-1);
- if (releaseSemaphore) {
- // Clean up, just in case
- getVolunteeringSemaphore().release();
- releaseSemaphore = false;
+ try {
+ queuedWork.run();
+ } catch (CancelException e) {
+ return;
+ } catch (RuntimeException e) {
+ // log and continue consuming queue
+ logger.error(e.getMessage(), e);
}
}
+ } finally {
+ getPartitionedRegionStats().incVolunteeringThreads(-1);
+ if (releaseSemaphore) {
+ // Clean up, just in case
+ getVolunteeringSemaphore().release();
+ }
}
};
}
}
- public boolean setShadowBucketDestroyed(boolean destroyed) {
- return this.shadowBucketDestroyed = destroyed;
+ void setShadowBucketDestroyed(boolean destroyed) {
+ shadowBucketDestroyed = destroyed;
}
public boolean getShadowBucketDestroyed() {
- return this.shadowBucketDestroyed;
+ return shadowBucketDestroyed;
}
}
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/BucketRegion.java b/geode-core/src/main/java/org/apache/geode/internal/cache/BucketRegion.java
index 001ac1e..f1c7018 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/BucketRegion.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/BucketRegion.java
@@ -12,6 +12,7 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
+
package org.apache.geode.internal.cache;
import java.io.DataOutput;
@@ -20,7 +21,6 @@ import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
@@ -109,7 +109,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
private static final Logger logger = LogService.getLogger();
@Immutable
- public static final RawValue NULLVALUE = new RawValue(null);
+ private static final RawValue NULLVALUE = new RawValue(null);
@Immutable
public static final RawValue REQUIRES_ENTRY_LOCK = new RawValue(null);
/**
@@ -135,34 +135,34 @@ public class BucketRegion extends DistributedRegion implements Bucket {
private final Object rawValue;
public RawValue(Object rawVal) {
- this.rawValue = rawVal;
+ rawValue = rawVal;
}
public boolean isValueByteArray() {
- return this.rawValue instanceof byte[];
+ return rawValue instanceof byte[];
}
public Object getRawValue() {
- return this.rawValue;
+ return rawValue;
}
public void writeAsByteArray(DataOutput out) throws IOException {
if (isValueByteArray()) {
- DataSerializer.writeByteArray((byte[]) this.rawValue, out);
- } else if (this.rawValue instanceof CachedDeserializable) {
- ((CachedDeserializable) this.rawValue).writeValueAsByteArray(out);
- } else if (Token.isInvalid(this.rawValue)) {
+ DataSerializer.writeByteArray((byte[]) rawValue, out);
+ } else if (rawValue instanceof CachedDeserializable) {
+ ((CachedDeserializable) rawValue).writeValueAsByteArray(out);
+ } else if (Token.isInvalid(rawValue)) {
DataSerializer.writeByteArray(null, out);
- } else if (this.rawValue == Token.TOMBSTONE) {
+ } else if (rawValue == Token.TOMBSTONE) {
DataSerializer.writeByteArray(null, out);
} else {
- DataSerializer.writeObjectAsByteArray(this.rawValue, out);
+ DataSerializer.writeObjectAsByteArray(rawValue, out);
}
}
@Override
public String toString() {
- return "RawValue(" + this.rawValue + ")";
+ return "RawValue(" + rawValue + ")";
}
/**
@@ -179,48 +179,46 @@ public class BucketRegion extends DistributedRegion implements Bucket {
if (isValueByteArray()) {
if (copyOnRead) {
// TODO move this code to CopyHelper.copy?
- byte[] src = (byte[]) this.rawValue;
+ byte[] src = (byte[]) rawValue;
byte[] dest = new byte[src.length];
- System.arraycopy(this.rawValue, 0, dest, 0, dest.length);
+ System.arraycopy(rawValue, 0, dest, 0, dest.length);
return dest;
} else {
- return this.rawValue;
+ return rawValue;
}
- } else if (this.rawValue instanceof CachedDeserializable) {
+ } else if (rawValue instanceof CachedDeserializable) {
if (copyOnRead) {
- return ((CachedDeserializable) this.rawValue).getDeserializedWritableCopy(null, null);
+ return ((CachedDeserializable) rawValue).getDeserializedWritableCopy(null, null);
} else {
- return ((CachedDeserializable) this.rawValue).getDeserializedForReading();
+ return ((CachedDeserializable) rawValue).getDeserializedForReading();
}
- } else if (Token.isInvalid(this.rawValue)) {
+ } else if (Token.isInvalid(rawValue)) {
return null;
} else {
if (copyOnRead) {
- return CopyHelper.copy(this.rawValue);
+ return CopyHelper.copy(rawValue);
} else {
- return this.rawValue;
+ return rawValue;
}
}
}
}
- private static final long serialVersionUID = 1L;
-
private final int redundancy;
/** the partitioned region to which this bucket belongs */
private final PartitionedRegion partitionedRegion;
- private final Map<Object, ExpiryTask> pendingSecondaryExpires = new HashMap<Object, ExpiryTask>();
+ private final Map<Object, ExpiryTask> pendingSecondaryExpires = new HashMap<>();
/* one map per bucket region */
- public HashMap allKeysMap = new HashMap();
+ private final HashMap<Object, LockObject> allKeysMap = new HashMap<>();
static final boolean FORCE_LOCAL_LISTENERS_INVOCATION = Boolean
.getBoolean(DistributionConfig.GEMFIRE_PREFIX + "BucketRegion.alwaysFireLocalListeners");
private volatile AtomicLong5 eventSeqNum = null;
- public AtomicLong5 getEventSeqNum() {
+ AtomicLong5 getEventSeqNum() {
return eventSeqNum;
}
@@ -238,8 +236,8 @@ public class BucketRegion extends DistributedRegion implements Bucket {
Assert.assertTrue(!isUsedForPartitionedRegionAdmin());
Assert.assertTrue(internalRegionArgs.getBucketAdvisor() != null);
Assert.assertTrue(internalRegionArgs.getPartitionedRegion() != null);
- this.redundancy = internalRegionArgs.getPartitionedRegionBucketRedundancy();
- this.partitionedRegion = internalRegionArgs.getPartitionedRegion();
+ redundancy = internalRegionArgs.getPartitionedRegionBucketRedundancy();
+ partitionedRegion = internalRegionArgs.getPartitionedRegion();
setEventSeqNum();
}
@@ -271,25 +269,25 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
private void setEventSeqNum() {
- if (this.partitionedRegion.isShadowPR() && this.partitionedRegion.getColocatedWith() != null) {
- PartitionedRegion parentPR = ColocationHelper.getLeaderRegion(this.partitionedRegion);
+ if (partitionedRegion.isShadowPR() && partitionedRegion.getColocatedWith() != null) {
+ PartitionedRegion parentPR = ColocationHelper.getLeaderRegion(partitionedRegion);
BucketRegion parentBucket = parentPR.getDataStore().getLocalBucketById(getId());
// needs to be set only once.
if (parentBucket.eventSeqNum == null) {
parentBucket.eventSeqNum = new AtomicLong5(getId());
}
}
- if (this.partitionedRegion.getColocatedWith() == null) {
- this.eventSeqNum = new AtomicLong5(getId());
+ if (partitionedRegion.getColocatedWith() == null) {
+ eventSeqNum = new AtomicLong5(getId());
} else {
- PartitionedRegion parentPR = ColocationHelper.getLeaderRegion(this.partitionedRegion);
+ PartitionedRegion parentPR = ColocationHelper.getLeaderRegion(partitionedRegion);
BucketRegion parentBucket = parentPR.getDataStore().getLocalBucketById(getId());
if (parentBucket == null && logger.isDebugEnabled()) {
logger.debug("The parentBucket of region {} bucketId {} is NULL",
- this.partitionedRegion.getFullPath(), getId());
+ partitionedRegion.getFullPath(), getId());
}
Assert.assertTrue(parentBucket != null);
- this.eventSeqNum = parentBucket.eventSeqNum;
+ eventSeqNum = parentBucket.eventSeqNum;
}
}
@@ -309,14 +307,14 @@ public class BucketRegion extends DistributedRegion implements Bucket {
@Override
public void registerCreateRegionReplyProcessor(CreateRegionReplyProcessor processor) {
- this.createRegionReplyProcessor = processor;
+ createRegionReplyProcessor = processor;
}
@Override
protected void recordEventStateFromImageProvider(InternalDistributedMember provider) {
- if (this.createRegionReplyProcessor != null) {
+ if (createRegionReplyProcessor != null) {
Map<ThreadIdentifier, EventSequenceNumberHolder> providerEventStates =
- this.createRegionReplyProcessor.getEventState(provider);
+ createRegionReplyProcessor.getEventState(provider);
if (providerEventStates != null) {
recordEventState(provider, providerEventStates);
} else {
@@ -327,7 +325,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// This will not cause data inconsistent issue. Log this message for debug purpose.
logger.info("Could not initiate event tracker from GII provider {}", provider);
}
- this.createRegionReplyProcessor = null;
+ createRegionReplyProcessor = null;
}
}
@@ -369,10 +367,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
if (clientRouting != null) {
return true;
}
- if (getFilterProfile() != null) {
- return true;
- }
- return false;
+ return getFilterProfile() != null;
}
@Override
@@ -408,18 +403,18 @@ public class BucketRegion extends DistributedRegion implements Bucket {
*
* @return first key found in CM null means not found
*/
- LockObject searchAndLock(Object keys[]) {
+ LockObject searchAndLock(Object[] keys) {
final boolean isDebugEnabled = logger.isDebugEnabled();
LockObject foundLock = null;
synchronized (allKeysMap) {
// check if there's any key in map
- for (int i = 0; i < keys.length; i++) {
- if (allKeysMap.containsKey(keys[i])) {
- foundLock = (LockObject) allKeysMap.get(keys[i]);
+ for (Object key : keys) {
+ if (allKeysMap.containsKey(key)) {
+ foundLock = allKeysMap.get(key);
if (isDebugEnabled) {
- logger.debug("LockKeys: found key: {}:{}", keys[i], foundLock.lockedTimeStamp);
+ logger.debug("LockKeys: found key: {}:{}", key, foundLock.lockedTimeStamp);
}
foundLock.waiting();
break;
@@ -428,12 +423,12 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// save the keys when still locked
if (foundLock == null) {
- for (int i = 0; i < keys.length; i++) {
+ for (Object key : keys) {
LockObject lockValue =
- new LockObject(keys[i], isDebugEnabled ? System.currentTimeMillis() : 0);
- allKeysMap.put(keys[i], lockValue);
+ new LockObject(key, isDebugEnabled ? System.currentTimeMillis() : 0);
+ allKeysMap.put(key, lockValue);
if (isDebugEnabled) {
- logger.debug("LockKeys: add key: {}:{}", keys[i], lockValue.lockedTimeStamp);
+ logger.debug("LockKeys: add key: {}:{}", key, lockValue.lockedTimeStamp);
}
}
}
@@ -446,19 +441,19 @@ public class BucketRegion extends DistributedRegion implements Bucket {
* After processed the keys, this method will remove them from CM. And notifyAll for each key. The
* thread needs to acquire lock of CM first.
*/
- public void removeAndNotifyKeys(Object keys[]) {
+ public void removeAndNotifyKeys(Object[] keys) {
final boolean isTraceEnabled = logger.isTraceEnabled();
synchronized (allKeysMap) {
- for (int i = 0; i < keys.length; i++) {
- LockObject lockValue = (LockObject) allKeysMap.remove(keys[i]);
+ for (Object key : keys) {
+ LockObject lockValue = allKeysMap.remove(key);
if (lockValue != null) {
// let current thread become the monitor of the key object
synchronized (lockValue) {
lockValue.setRemoved();
if (isTraceEnabled) {
long waitTime = System.currentTimeMillis() - lockValue.lockedTimeStamp;
- logger.trace("LockKeys: remove key {}, notifyAll for {}. It waited {}", keys[i],
+ logger.trace("LockKeys: remove key {}, notifyAll for {}. It waited {}", key,
lockValue, waitTime);
}
if (lockValue.isSomeoneWaiting()) {
@@ -475,7 +470,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
* This method will block current thread for long time. It only exits when current thread
* successfully save its keys into CM.
*/
- public boolean waitUntilLocked(Object keys[]) {
+ public boolean waitUntilLocked(Object[] keys) {
final boolean isDebugEnabled = logger.isDebugEnabled();
final String title = "BucketRegion.waitUntilLocked:";
@@ -524,12 +519,12 @@ public class BucketRegion extends DistributedRegion implements Bucket {
boolean locked = lockKeysAndPrimary(event);
try {
- if (this.partitionedRegion.isParallelWanEnabled()) {
+ if (partitionedRegion.isParallelWanEnabled()) {
handleWANEvent(event);
}
if (!hasSeenEvent(event)) {
forceSerialized(event);
- RegionEntry oldEntry = this.entries.basicPut(event, lastModified, ifNew, ifOld,
+ RegionEntry oldEntry = entries.basicPut(event, lastModified, ifNew, ifOld,
expectedOldValue, requireOldValue, overwriteDestroyed);
return oldEntry != null;
}
@@ -560,22 +555,22 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
- public long generateTailKey() {
- long key = this.eventSeqNum.addAndGet(this.partitionedRegion.getTotalNumberOfBuckets());
+ long generateTailKey() {
+ long key = eventSeqNum.addAndGet(partitionedRegion.getTotalNumberOfBuckets());
if (key < 0 || key % getPartitionedRegion().getTotalNumberOfBuckets() != getId()) {
logger.error("ERROR! The sequence number {} generated for the bucket {} is incorrect.",
new Object[] {key, getId()});
}
if (logger.isDebugEnabled()) {
logger.debug("WAN: On primary bucket {}, setting the seq number as {}", getId(),
- this.eventSeqNum.get());
+ eventSeqNum.get());
}
return eventSeqNum.get();
}
@Override
public void handleWANEvent(EntryEventImpl event) {
- if (this.eventSeqNum == null) {
+ if (eventSeqNum == null) {
if (logger.isDebugEnabled()) {
logger.debug(
"The bucket corresponding to this user bucket is not created yet. This event will not go to remote wan site. Event: {}",
@@ -585,7 +580,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
if (!(this instanceof AbstractBucketRegionQueue)) {
if (getBucketAdvisor().isPrimary()) {
- long key = this.eventSeqNum.addAndGet(this.partitionedRegion.getTotalNumberOfBuckets());
+ long key = eventSeqNum.addAndGet(partitionedRegion.getTotalNumberOfBuckets());
if (key < 0 || key % getPartitionedRegion().getTotalNumberOfBuckets() != getId()) {
logger.error("ERROR! The sequence number {} generated for the bucket {} is incorrect.",
new Object[] {key, getId()});
@@ -593,7 +588,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
event.setTailKey(key);
if (logger.isDebugEnabled()) {
logger.debug("WAN: On primary bucket {}, setting the seq number as {}", getId(),
- this.eventSeqNum.get());
+ eventSeqNum.get());
}
} else {
// Can there be a race here? Like one thread has done put in primary but
@@ -601,7 +596,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// in that case its possible that a tail key is missed.
// we can handle that by only incrementing the tailKey and never
// setting it less than the current value.
- Atomics.setIfGreater(this.eventSeqNum, event.getTailKey());
+ Atomics.setIfGreater(eventSeqNum, event.getTailKey());
if (logger.isDebugEnabled()) {
logger.debug("WAN: On secondary bucket {}, setting the seq number as {}", getId(),
event.getTailKey());
@@ -614,8 +609,8 @@ public class BucketRegion extends DistributedRegion implements Bucket {
* Fix for Bug#45917 We are updating the seqNumber so that new seqNumbers are generated starting
* from the latest in the system.
*/
- public void updateEventSeqNum(long l) {
- Atomics.setIfGreater(this.eventSeqNum, l);
+ void updateEventSeqNum(long l) {
+ Atomics.setIfGreater(eventSeqNum, l);
if (logger.isDebugEnabled()) {
logger.debug("WAN: On bucket {}, setting the seq number as {} before GII", getId(), l);
}
@@ -630,13 +625,13 @@ public class BucketRegion extends DistributedRegion implements Bucket {
if (event.isBulkOpInProgress()) {
// consolidate the UpdateOperation for each entry into a PutAllMessage
// since we did not call basicPutPart3(), so we have to explicitly addEntry here
- event.getPutAllOperation().addEntry(event, this.getId());
+ event.getPutAllOperation().addEntry(event, getId());
} else {
// before distribute: BR's put
op = new UpdateOperation(event, lastModified);
token = op.startOperation();
if (logger.isDebugEnabled()) {
- logger.debug("sent update operation : for region : {}: with event: {}", this.getName(),
+ logger.debug("sent update operation : for region : {}: with event: {}", getName(),
event);
}
}
@@ -669,7 +664,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
try {
// Update the get stats if necessary.
- if (this.partitionedRegion.getDataStore().hasClientInterest(event)) {
+ if (partitionedRegion.getDataStore().hasClientInterest(event)) {
updateStatsForGet(entry, true);
}
if (!event.isOriginRemote()) {
@@ -678,7 +673,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
VersionTag v = entry.generateVersionTag(null, eventHasDelta, this, event);
if (v != null) {
if (logger.isDebugEnabled()) {
- logger.debug("generated version tag {} in region {}", v, this.getName());
+ logger.debug("generated version tag {} in region {}", v, getName());
}
}
}
@@ -689,13 +684,13 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// ops
if (!event.isBulkOpInProgress()) {
- long start = this.partitionedRegion.getPrStats().startSendReplication();
+ long start = partitionedRegion.getPrStats().startSendReplication();
try {
// before distribute: PR's put PR
op = new UpdateOperation(event, modifiedTime);
token = op.startOperation();
} finally {
- this.partitionedRegion.getPrStats().endSendReplication(start);
+ partitionedRegion.getPrStats().endSendReplication(start);
}
} else {
// consolidate the UpdateOperation for each entry into a PutAllMessage
@@ -703,9 +698,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
}
- long lastModifiedTime =
- super.basicPutPart2(event, entry, isInitialized, lastModified, clearConflict);
- return lastModifiedTime;
+ return super.basicPutPart2(event, entry, isInitialized, lastModified, clearConflict);
} finally {
if (op != null) {
op.endOperation(token);
@@ -719,8 +712,8 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// Preserve the bucket reference for resetting it later.
InternalRegion bucketRegion = event.getRegion();
try {
- event.setRegion(this.partitionedRegion);
- this.partitionedRegion.notifyGatewaySender(operation, event);
+ event.setRegion(partitionedRegion);
+ partitionedRegion.notifyGatewaySender(operation, event);
} finally {
// reset the event region back to bucket region.
// This should work as gateway queue create GatewaySenderEvent for
@@ -732,7 +725,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
public void checkForPrimary() {
final boolean isp = getBucketAdvisor().isPrimary();
if (!isp) {
- this.partitionedRegion.checkReadiness();
+ partitionedRegion.checkReadiness();
checkReadiness();
InternalDistributedMember primaryHolder = getBucketAdvisor().basicGetPrimaryMember();
throw new PrimaryBucketException(
@@ -772,7 +765,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
Object[] getKeysToBeLocked(EntryEventImpl event) {
- Object keys[] = new Object[1];
+ Object[] keys = new Object[1];
keys[0] = event.getKey();
return keys;
}
@@ -930,7 +923,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
boolean forceCallbacks = isEntryEvictDestroyEnabled();
boolean done =
- this.entries.invalidate(event, invokeCallbacks, forceNewEntry, forceCallbacks);
+ entries.invalidate(event, invokeCallbacks, forceNewEntry, forceCallbacks);
ExpirationAction expirationAction = getEntryExpirationAction();
if (done && !getBucketAdvisor().isPrimary() && expirationAction != null
&& expirationAction.isInvalidate()) {
@@ -938,7 +931,6 @@ public class BucketRegion extends DistributedRegion implements Bucket {
pendingSecondaryExpires.remove(event.getKey());
}
}
- return;
} else {
if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) {
logger.trace(LogMarker.DM_VERBOSE,
@@ -947,7 +939,6 @@ public class BucketRegion extends DistributedRegion implements Bucket {
if (!getConcurrencyChecksEnabled() || event.hasValidVersionTag()) {
distributeInvalidateOperation(event);
}
- return;
}
} finally {
if (locked) {
@@ -987,7 +978,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
if (event.getVersionTag() == null || event.getVersionTag().isGatewayTag()) {
VersionTag v = regionEntry.generateVersionTag(null, false, this, event);
if (logger.isDebugEnabled() && v != null) {
- logger.debug("generated version tag {} in region {}", v, this.getName());
+ logger.debug("generated version tag {} in region {}", v, getName());
}
event.setVersionTag(v);
}
@@ -1021,7 +1012,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// send InvalidateRegion message.
event.region = this;
super.distributeInvalidateRegion(event);
- event.region = this.partitionedRegion;
+ event.region = partitionedRegion;
}
@Override
@@ -1034,7 +1025,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
if (event.getOperation().isLocal()) { // bug #45402 - localDestroy generated a version tag
return false;
}
- return this.getConcurrencyChecksEnabled()
+ return getConcurrencyChecksEnabled()
&& ((event.getVersionTag() == null) || event.getVersionTag().isGatewayTag());
}
@@ -1047,10 +1038,8 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
try {
super.expireDestroy(event, cacheWrite);
- return;
- } catch (PrimaryBucketException e) {
+ } catch (PrimaryBucketException ignored) {
// must have concurrently removed the primary
- return;
}
}
@@ -1068,7 +1057,6 @@ public class BucketRegion extends DistributedRegion implements Bucket {
@Override
void performExpiryTimeout(ExpiryTask expiryTask) throws CacheException {
- ExpiryTask task = expiryTask;
boolean isEvictDestroy = isEntryEvictDestroyEnabled();
// Fix for bug 43805 - get the primary lock before
// synchronizing on pendingSecondaryExpires, to match the lock
@@ -1078,50 +1066,50 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// Why do we care if evict destroy is configured?
// See bug 41096 for the answer.
if (!getBucketAdvisor().isPrimary() && !isEvictDestroy) {
- synchronized (this.pendingSecondaryExpires) {
- if (task.isPending()) {
- Object key = task.getKey();
+ synchronized (pendingSecondaryExpires) {
+ if (expiryTask.isPending()) {
+ Object key = expiryTask.getKey();
if (key != null) {
- this.pendingSecondaryExpires.put(key, task);
+ pendingSecondaryExpires.put(key, expiryTask);
}
}
}
} else {
- super.performExpiryTimeout(task);
+ super.performExpiryTimeout(expiryTask);
}
} finally {
doUnlockForPrimary();
}
}
- protected boolean isEntryEvictDestroyEnabled() {
+ private boolean isEntryEvictDestroyEnabled() {
return getEvictionAttributes() != null
&& EvictionAction.LOCAL_DESTROY.equals(getEvictionAttributes().getAction());
}
- protected void processPendingSecondaryExpires() {
+ void processPendingSecondaryExpires() {
ExpiryTask[] tasks;
while (true) {
// note we just keep looping until no more pendingExpires exist
- synchronized (this.pendingSecondaryExpires) {
- if (this.pendingSecondaryExpires.isEmpty()) {
+ synchronized (pendingSecondaryExpires) {
+ if (pendingSecondaryExpires.isEmpty()) {
return;
}
- tasks = new ExpiryTask[this.pendingSecondaryExpires.size()];
- tasks = this.pendingSecondaryExpires.values().toArray(tasks);
- this.pendingSecondaryExpires.clear();
+ tasks = new ExpiryTask[pendingSecondaryExpires.size()];
+ tasks = pendingSecondaryExpires.values().toArray(tasks);
+ pendingSecondaryExpires.clear();
}
try {
- if (isCacheClosing() || isClosed() || this.isDestroyed) {
+ if (isCacheClosing() || isClosed() || isDestroyed) {
return;
}
final boolean isDebugEnabled = logger.isDebugEnabled();
- for (int i = 0; i < tasks.length; i++) {
+ for (ExpiryTask task : tasks) {
try {
if (isDebugEnabled) {
- logger.debug("{} fired at {}", tasks[i], System.currentTimeMillis());
+ logger.debug("{} fired at {}", task, System.currentTimeMillis());
}
- tasks[i].basicPerformTimeout(true);
+ task.basicPerformTimeout(true);
if (isCacheClosing() || isClosed() || isDestroyed()) {
return;
}
@@ -1129,9 +1117,9 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// ignore and try the next expiry task
}
}
- } catch (RegionDestroyedException re) {
+ } catch (RegionDestroyedException ignored) {
// Ignore - our job is done
- } catch (CancelException ex) {
+ } catch (CancelException ignored) {
// ignore
} catch (VirtualMachineError err) {
SystemFailure.initiateFailure(err);
@@ -1185,7 +1173,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
boolean locked = lockKeysAndPrimary(event);
try {
// increment the tailKey for the destroy event
- if (this.partitionedRegion.isParallelWanEnabled()) {
+ if (partitionedRegion.isParallelWanEnabled()) {
handleWANEvent(event);
}
// This call should invoke AbstractRegionMap (aka ARM) destroy method
@@ -1211,12 +1199,10 @@ public class BucketRegion extends DistributedRegion implements Bucket {
pendingSecondaryExpires.remove(event.getKey());
}
}
- return;
} else {
if (!getConcurrencyChecksEnabled() || event.hasValidVersionTag()) {
distributeDestroyOperation(event);
}
- return;
}
} finally {
if (locked) {
@@ -1237,7 +1223,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
if (!event.isOriginRemote() && getBucketAdvisor().isPrimary()) {
if (event.isBulkOpInProgress()) {
// consolidate the DestroyOperation for each entry into a RemoveAllMessage
- event.getRemoveAllOperation().addEntry(event, this.getId());
+ event.getRemoveAllOperation().addEntry(event, getId());
} else {
// This cache has processed the event, forward operation
// and event messages to backup buckets
@@ -1271,7 +1257,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
if (event.getVersionTag() == null || event.getVersionTag().isGatewayTag()) {
VersionTag v = entry.generateVersionTag(null, false, this, event);
if (logger.isDebugEnabled() && v != null) {
- logger.debug("generated version tag {} in region {}", v, this.getName());
+ logger.debug("generated version tag {} in region {}", v, getName());
}
}
@@ -1360,7 +1346,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
boolean keysAndPrimaryLocked = lockKeysAndPrimary(event);
try {
if (!hasSeenEvent(event)) {
- this.entries.updateEntryVersion(event);
+ entries.updateEntryVersion(event);
} else {
if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) {
logger.trace(LogMarker.DM_VERBOSE,
@@ -1374,7 +1360,6 @@ public class BucketRegion extends DistributedRegion implements Bucket {
distributeUpdateEntryVersionOperation(event);
}
}
- return;
} finally {
if (keysAndPrimaryLocked) {
releaseLockForKeysAndPrimary(event);
@@ -1393,14 +1378,13 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
public int getRedundancyLevel() {
- return this.redundancy;
+ return redundancy;
}
@Override
public boolean isPrimary() {
throw new UnsupportedOperationException(
- String.format("This should never be called on %s",
- getClass()));
+ String.format("This should never be called on %s", getClass()));
}
@Override
@@ -1410,8 +1394,8 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// for local region, which is before this final field is assigned. This is why
// we shouldn't do some much work in the constructors! This is a temporary
// hack until I move must of the constructor code to region.initialize.
- return isBucketDestroyed() || (this.partitionedRegion != null
- && this.partitionedRegion.isLocallyDestroyed && !isInDestroyingThread());
+ return isBucketDestroyed() || (partitionedRegion != null
+ && partitionedRegion.isLocallyDestroyed && !isInDestroyingThread());
}
/**
@@ -1439,27 +1423,27 @@ public class BucketRegion extends DistributedRegion implements Bucket {
@Override
public PartitionedRegion getPartitionedRegion() {
- return this.partitionedRegion;
+ return partitionedRegion;
}
/**
* is the current thread involved in destroying the PR that owns this region?
*/
private boolean isInDestroyingThread() {
- return this.partitionedRegion.locallyDestroyingThread == Thread.currentThread();
+ return partitionedRegion.locallyDestroyingThread == Thread.currentThread();
}
@Override
public void fillInProfile(Profile profile) {
super.fillInProfile(profile);
BucketProfile bp = (BucketProfile) profile;
- bp.isInitializing = this.getInitializationLatchAfterGetInitialImage().getCount() > 0;
+ bp.isInitializing = getInitializationLatchAfterGetInitialImage().getCount() > 0;
}
/** check to see if the partitioned region is locally destroyed or closed */
- public boolean isPartitionedRegionOpen() {
- return !this.partitionedRegion.isLocallyDestroyed && !this.partitionedRegion.isClosed
- && !this.partitionedRegion.isDestroyed();
+ boolean isPartitionedRegionOpen() {
+ return !partitionedRegion.isLocallyDestroyed && !partitionedRegion.isClosed
+ && !partitionedRegion.isDestroyed();
}
/**
@@ -1469,22 +1453,19 @@ public class BucketRegion extends DistributedRegion implements Bucket {
* @param returnTombstones whether Token.TOMBSTONE should be returned for destroyed entries
* @return serialized form if present, null if the entry is not in the cache, or INVALID or
* LOCAL_INVALID re is a miss (invalid)
- * @throws IOException if there is a serialization problem see
- * LocalRegion#getDeserializedValue(RegionEntry, KeyInfo, boolean, boolean, boolean,
- * EntryEventImpl, boolean, boolean, boolean)
*/
private RawValue getSerialized(Object key, boolean updateStats, boolean doNotLockEntry,
EntryEventImpl clientEvent, boolean returnTombstones)
- throws EntryNotFoundException, IOException {
- RegionEntry re = null;
- re = this.entries.getEntry(key);
+ throws EntryNotFoundException {
+ RegionEntry re;
+ re = entries.getEntry(key);
if (re == null) {
return NULLVALUE;
}
if (re.isTombstone() && !returnTombstones) {
return NULLVALUE;
}
- Object v = null;
+ Object v;
try {
v = re.getValue(this);
@@ -1500,7 +1481,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
}
} catch (DiskAccessException dae) {
- this.handleDiskAccessException(dae);
+ handleDiskAccessException(dae);
throw dae;
}
@@ -1534,8 +1515,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
boolean miss = true;
try {
- RawValue valueBytes = NULLVALUE;
- boolean isCreate = false;
+ boolean isCreate;
RawValue result =
getSerialized(keyInfo.getKey(), true, doNotLockEntry, clientEvent, returnTombstones);
isCreate =
@@ -1568,16 +1548,16 @@ public class BucketRegion extends DistributedRegion implements Bucket {
@Override
public String toString() {
- return new StringBuilder().append("BucketRegion").append("[path='").append(getFullPath())
- .append(";serial=").append(getSerialNumber()).append(";primary=")
- .append(getBucketAdvisor().getProxyBucketRegion().isPrimary()).append("]").toString();
+ return "BucketRegion" + "[path='" + getFullPath()
+ + ";serial=" + getSerialNumber() + ";primary="
+ + getBucketAdvisor().getProxyBucketRegion().isPrimary() + "]";
}
@Override
protected void distributedRegionCleanup(RegionEventImpl event) {
// No need to close advisor, assume its already closed
// However we need to remove our listener from the advisor (see bug 43950).
- this.distAdvisor.removeMembershipListener(this.advisorListener);
+ distAdvisor.removeMembershipListener(advisorListener);
}
/**
@@ -1588,7 +1568,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
*
* @param rebalance true if this is due to a rebalance removing the bucket
*/
- public void removeFromPeersAdvisors(boolean rebalance) {
+ void removeFromPeersAdvisors(boolean rebalance) {
if (getPersistenceAdvisor() != null) {
getPersistenceAdvisor().releaseTieLock();
}
@@ -1627,17 +1607,17 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
@Retained
- EntryEventImpl createEventForPR(EntryEventImpl sourceEvent) {
+ private EntryEventImpl createEventForPR(EntryEventImpl sourceEvent) {
EntryEventImpl e2 = new EntryEventImpl(sourceEvent);
boolean returned = false;
try {
- e2.setRegion(this.partitionedRegion);
+ e2.setRegion(partitionedRegion);
if (FORCE_LOCAL_LISTENERS_INVOCATION) {
e2.setInvokePRCallbacks(true);
} else {
e2.setInvokePRCallbacks(sourceEvent.getInvokePRCallbacks());
}
- DistributedMember dm = this.getDistributionManager().getDistributionManagerId();
+ DistributedMember dm = getDistributionManager().getDistributionManagerId();
e2.setOriginRemote(!e2.getDistributedMember().equals(dm));
returned = true;
return e2;
@@ -1659,7 +1639,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// bucket events may make it to this point even though the bucket is still
// initializing. We can't block while initializing or a GII state flush
// may hang, so we avoid notifying the bucket
- if (this.isInitialized()) {
+ if (isInitialized()) {
boolean callThem = callDispatchListenerEvent;
if (event.isPossibleDuplicate()
&& getEventTracker().isInitialImageProvider(event.getDistributedMember())) {
@@ -1670,8 +1650,8 @@ public class BucketRegion extends DistributedRegion implements Bucket {
@Released
final EntryEventImpl prevent = createEventForPR(event);
try {
- this.partitionedRegion.invokeTXCallbacks(eventType, prevent,
- this.partitionedRegion.isInitialized() ? callDispatchListenerEvent : false);
+ partitionedRegion.invokeTXCallbacks(eventType, prevent,
+ partitionedRegion.isInitialized() && callDispatchListenerEvent);
} finally {
prevent.release();
}
@@ -1691,10 +1671,10 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// bucket events may make it to this point even though the bucket is still
// initializing. We can't block while initializing or a GII state flush
// may hang, so we avoid notifying the bucket
- if (this.isInitialized()) {
+ if (isInitialized()) {
boolean callThem = callDispatchListenerEvent;
if (event.isPossibleDuplicate()
- && this.getEventTracker().isInitialImageProvider(event.getDistributedMember())) {
+ && getEventTracker().isInitialImageProvider(event.getDistributedMember())) {
callThem = false;
}
super.invokeDestroyCallbacks(eventType, event, callThem, notifyGateways);
@@ -1702,8 +1682,8 @@ public class BucketRegion extends DistributedRegion implements Bucket {
@Released
final EntryEventImpl prevent = createEventForPR(event);
try {
- this.partitionedRegion.invokeDestroyCallbacks(eventType, prevent,
- this.partitionedRegion.isInitialized() ? callDispatchListenerEvent : false, false);
+ partitionedRegion.invokeDestroyCallbacks(eventType, prevent,
+ partitionedRegion.isInitialized() && callDispatchListenerEvent, false);
} finally {
prevent.release();
}
@@ -1722,10 +1702,10 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// bucket events may make it to this point even though the bucket is still
// initializing. We can't block while initializing or a GII state flush
// may hang, so we avoid notifying the bucket
- if (this.isInitialized()) {
+ if (isInitialized()) {
boolean callThem = callDispatchListenerEvent;
if (event.isPossibleDuplicate()
- && this.getEventTracker().isInitialImageProvider(event.getDistributedMember())) {
+ && getEventTracker().isInitialImageProvider(event.getDistributedMember())) {
callThem = false;
}
super.invokeInvalidateCallbacks(eventType, event, callThem);
@@ -1733,8 +1713,8 @@ public class BucketRegion extends DistributedRegion implements Bucket {
@Released
final EntryEventImpl prevent = createEventForPR(event);
try {
- this.partitionedRegion.invokeInvalidateCallbacks(eventType, prevent,
- this.partitionedRegion.isInitialized() ? callDispatchListenerEvent : false);
+ partitionedRegion.invokeInvalidateCallbacks(eventType, prevent,
+ partitionedRegion.isInitialized() && callDispatchListenerEvent);
} finally {
prevent.release();
}
@@ -1756,10 +1736,10 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// bucket events may make it to this point even though the bucket is still
// initializing. We can't block while initializing or a GII state flush
// may hang, so we avoid notifying the bucket
- if (this.isInitialized()) {
+ if (isInitialized()) {
boolean callThem = callDispatchListenerEvent;
if (callThem && event.isPossibleDuplicate()
- && this.getEventTracker().isInitialImageProvider(event.getDistributedMember())) {
+ && getEventTracker().isInitialImageProvider(event.getDistributedMember())) {
callThem = false;
}
super.invokePutCallbacks(eventType, event, callThem, notifyGateways);
@@ -1768,29 +1748,27 @@ public class BucketRegion extends DistributedRegion implements Bucket {
@Released
final EntryEventImpl prevent = createEventForPR(event);
try {
- this.partitionedRegion.invokePutCallbacks(eventType, prevent,
- this.partitionedRegion.isInitialized() ? callDispatchListenerEvent : false, false);
+ partitionedRegion.invokePutCallbacks(eventType, prevent,
+ partitionedRegion.isInitialized() && callDispatchListenerEvent, false);
} finally {
prevent.release();
}
}
/**
- * perform adjunct messaging for the given operation and return a set of members that should be
- * attached to the operation's reply processor (if any)
+ * perform adjunct messaging for the given operation
*
* @param event the event causing this messaging
* @param cacheOpRecipients set of receiver which got cacheUpdateOperation.
* @param adjunctRecipients recipients that must unconditionally get the event
* @param filterRoutingInfo routing information for all members having the region
* @param processor the reply processor, or null if there isn't one
- * @return the set of failed recipients
*/
- protected Set performAdjunctMessaging(EntryEventImpl event, Set cacheOpRecipients,
- Set adjunctRecipients, FilterRoutingInfo filterRoutingInfo, DirectReplyProcessor processor,
+ void performAdjunctMessaging(EntryEventImpl event, Set cacheOpRecipients,
+ Set adjunctRecipients, FilterRoutingInfo filterRoutingInfo,
+ DirectReplyProcessor processor,
boolean calculateDelta, boolean sendDeltaWithFullValue) {
- Set failures = Collections.emptySet();
PartitionMessage msg = event.getPartitionMessage();
if (calculateDelta) {
setDeltaIfNeeded(event);
@@ -1799,35 +1777,32 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// The primary bucket member which is being modified remotely by a
// thread via a received PartitionedMessage
msg = msg.getMessageForRelayToListeners(event, adjunctRecipients);
- msg.setSender(this.partitionedRegion.getDistributionManager().getDistributionManagerId());
+ msg.setSender(partitionedRegion.getDistributionManager().getDistributionManagerId());
msg.setSendDeltaWithFullValue(sendDeltaWithFullValue);
- failures = msg.relayToListeners(cacheOpRecipients, adjunctRecipients, filterRoutingInfo,
- event, this.partitionedRegion, processor);
+ msg.relayToListeners(cacheOpRecipients, adjunctRecipients, filterRoutingInfo,
+ event, partitionedRegion, processor);
} else {
// The primary bucket is being modified locally by an application thread locally
Operation op = event.getOperation();
if (op.isCreate() || op.isUpdate()) {
// note that at this point ifNew/ifOld have been used to update the
// local store, and the event operation should be correct
- failures = PutMessage.notifyListeners(cacheOpRecipients, adjunctRecipients,
- filterRoutingInfo, this.partitionedRegion, event, op.isCreate(), !op.isCreate(),
+ PutMessage.notifyListeners(cacheOpRecipients, adjunctRecipients,
+ filterRoutingInfo, partitionedRegion, event, op.isCreate(), !op.isCreate(),
processor, sendDeltaWithFullValue);
} else if (op.isDestroy()) {
- failures = DestroyMessage.notifyListeners(cacheOpRecipients, adjunctRecipients,
- filterRoutingInfo, this.partitionedRegion, event, processor);
+ DestroyMessage.notifyListeners(cacheOpRecipients, adjunctRecipients,
+ filterRoutingInfo, partitionedRegion, event, processor);
} else if (op.isInvalidate()) {
- failures = InvalidateMessage.notifyListeners(cacheOpRecipients, adjunctRecipients,
- filterRoutingInfo, this.partitionedRegion, event, processor);
- } else {
- failures = adjunctRecipients;
+ InvalidateMessage.notifyListeners(cacheOpRecipients, adjunctRecipients,
+ filterRoutingInfo, partitionedRegion, event, processor);
}
}
- return failures;
}
private void setDeltaIfNeeded(EntryEventImpl event) {
- if (this.partitionedRegion.getSystem().getConfig().getDeltaPropagation()
+ if (partitionedRegion.getSystem().getConfig().getDeltaPropagation()
&& event.getOperation().isUpdate() && event.getDeltaBytes() == null) {
@Unretained
Object rawNewValue = event.getRawNewValue();
@@ -1847,7 +1822,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
long start = DistributionStats.getStatTime();
((org.apache.geode.Delta) instance).toDelta(hdos);
event.setDeltaBytes(hdos.toByteArray());
- this.partitionedRegion.getCachePerfStats().endDeltaPrepared(start);
+ partitionedRegion.getCachePerfStats().endDeltaPrepared(start);
} catch (RuntimeException re) {
throw re;
} catch (Exception e) {
@@ -1868,45 +1843,14 @@ public class BucketRegion extends DistributedRegion implements Bucket {
* @param adjunctRecipients recipients that must unconditionally get the event
* @param filterRoutingInfo routing information for all members having the region
* @param processor the reply processor, or null if there isn't one
- * @return the set of failed recipients
*/
- public Set performPutAllAdjunctMessaging(DistributedPutAllOperation dpao, Set cacheOpRecipients,
- Set adjunctRecipients, FilterRoutingInfo filterRoutingInfo, DirectReplyProcessor processor) {
- // create a PutAllPRMessage out of PutAllMessage to send to adjunct nodes
+ void performPutAllAdjunctMessaging(DistributedPutAllOperation dpao, Set cacheOpRecipients,
+ Set<InternalDistributedMember> adjunctRecipients, FilterRoutingInfo filterRoutingInfo,
+ DirectReplyProcessor processor) {
PutAllPRMessage prMsg = dpao.createPRMessagesNotifyOnly(getId());
- prMsg.initMessage(this.partitionedRegion, adjunctRecipients, true, processor);
- prMsg.setSender(this.partitionedRegion.getDistributionManager().getDistributionManagerId());
-
- // find members who have clients subscribed to this event and add them
- // to the recipients list. Also determine if there are any FilterInfo
- // routing tables for any of the receivers
- // boolean anyWithRouting = false;
- Set recipients = null;
- Set membersWithRouting = filterRoutingInfo.getMembers();
- for (Iterator it = membersWithRouting.iterator(); it.hasNext();) {
- Object mbr = it.next();
- if (!cacheOpRecipients.contains(mbr)) {
- // anyWithRouting = true;
- if (!adjunctRecipients.contains(mbr)) {
- if (recipients == null) {
- recipients = new HashSet();
- recipients.add(mbr);
- }
- }
- }
- }
- if (recipients == null) {
- recipients = adjunctRecipients;
- } else {
- recipients.addAll(adjunctRecipients);
- }
-
- // Set failures = Collections.EMPTY_SET;
-
- // if (!anyWithRouting) {
- Set failures = this.partitionedRegion.getDistributionManager().putOutgoing(prMsg);
-
- return failures;
+ prMsg.initMessage(partitionedRegion, adjunctRecipients, true, processor);
+ prMsg.setSender(partitionedRegion.getDistributionManager().getDistributionManagerId());
+ partitionedRegion.getDistributionManager().putOutgoing(prMsg);
}
/**
@@ -1920,55 +1864,30 @@ public class BucketRegion extends DistributedRegion implements Bucket {
* @param processor the reply processor, or null if there isn't one
* @return the set of failed recipients
*/
- public Set performRemoveAllAdjunctMessaging(DistributedRemoveAllOperation op,
- Set cacheOpRecipients, Set adjunctRecipients, FilterRoutingInfo filterRoutingInfo,
+ void performRemoveAllAdjunctMessaging(DistributedRemoveAllOperation op,
+ Set cacheOpRecipients, Set<InternalDistributedMember> adjunctRecipients,
+ FilterRoutingInfo filterRoutingInfo,
DirectReplyProcessor processor) {
// create a RemoveAllPRMessage out of RemoveAllMessage to send to adjunct nodes
RemoveAllPRMessage prMsg = op.createPRMessagesNotifyOnly(getId());
- prMsg.initMessage(this.partitionedRegion, adjunctRecipients, true, processor);
- prMsg.setSender(this.partitionedRegion.getDistributionManager().getDistributionManagerId());
-
- // find members who have clients subscribed to this event and add them
- // to the recipients list. Also determine if there are any FilterInfo
- // routing tables for any of the receivers
- Set recipients = null;
- Set membersWithRouting = filterRoutingInfo.getMembers();
- for (Iterator it = membersWithRouting.iterator(); it.hasNext();) {
- Object mbr = it.next();
- if (!cacheOpRecipients.contains(mbr)) {
- // anyWithRouting = true;
- if (!adjunctRecipients.contains(mbr)) {
- if (recipients == null) {
- recipients = new HashSet();
- recipients.add(mbr);
- }
- }
- }
- }
- if (recipients == null) {
- recipients = adjunctRecipients;
- } else {
- recipients.addAll(adjunctRecipients);
- }
-
- Set failures = this.partitionedRegion.getDistributionManager().putOutgoing(prMsg);
- return failures;
+ prMsg.initMessage(partitionedRegion, adjunctRecipients, true, processor);
+ prMsg.setSender(partitionedRegion.getDistributionManager().getDistributionManagerId());
+ partitionedRegion.getDistributionManager().putOutgoing(prMsg);
}
/**
* return the set of recipients for adjunct operations
*/
- protected Set getAdjunctReceivers(EntryEventImpl event, Set cacheOpReceivers, Set twoMessages,
+ protected Set<InternalDistributedMember> getAdjunctReceivers(EntryEventImpl event,
+ Set<InternalDistributedMember> cacheOpReceivers, Set<InternalDistributedMember> twoMessages,
FilterRoutingInfo routing) {
Operation op = event.getOperation();
if (op.isUpdate() || op.isCreate() || op.isDestroy() || op.isInvalidate()) {
// this method can safely assume that the operation is being distributed from
// the primary bucket holder to other nodes
- Set r = this.partitionedRegion.getRegionAdvisor().adviseRequiresNotification(event);
-
- if (r.size() > 0) {
- r.removeAll(cacheOpReceivers);
- }
+ Set<InternalDistributedMember> r =
+ partitionedRegion.getRegionAdvisor().adviseRequiresNotification();
+ r.removeAll(cacheOpReceivers);
// buckets that are initializing may transition out of token mode during
// message transmission and need both cache-op and adjunct messages to
@@ -1985,7 +1904,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
for (InternalDistributedMember id : routing.getMembers()) {
if (!cacheOpReceivers.contains(id)) {
if (r.isEmpty()) {
- r = new HashSet();
+ r = new HashSet<>();
}
r.add(id);
}
@@ -2013,8 +1932,8 @@ public class BucketRegion extends DistributedRegion implements Bucket {
origRemoteState = event.isOriginRemote();
event.setOriginRemote(true);
}
- event.setRegion(this.partitionedRegion);
- this.partitionedRegion.cacheWriteBeforePut(event, netWriteRecipients, localWriter,
+ event.setRegion(partitionedRegion);
+ partitionedRegion.cacheWriteBeforePut(event, netWriteRecipients, localWriter,
requireOldValue, expectedOldValue);
} finally {
if (event.getPartitionMessage() != null || event.hasClientOrigin()) {
@@ -2029,27 +1948,24 @@ public class BucketRegion extends DistributedRegion implements Bucket {
throws CacheWriterException, EntryNotFoundException, TimeoutException {
boolean origRemoteState = false;
- boolean ret = false;
try {
if (event.getPartitionMessage() != null || event.hasClientOrigin()) {
origRemoteState = event.isOriginRemote();
event.setOriginRemote(true);
}
- event.setRegion(this.partitionedRegion);
- ret = this.partitionedRegion.cacheWriteBeforeDestroy(event, expectedOldValue);
+ event.setRegion(partitionedRegion);
+ return partitionedRegion.cacheWriteBeforeDestroy(event, expectedOldValue);
} finally {
if (event.getPartitionMessage() != null || event.hasClientOrigin()) {
event.setOriginRemote(origRemoteState);
}
event.setRegion(this);
}
- return ret;
- // return super.cacheWriteBeforeDestroy(event);
}
@Override
public CacheWriter basicGetWriter() {
- return this.partitionedRegion.basicGetWriter();
+ return partitionedRegion.basicGetWriter();
}
/*
@@ -2060,7 +1976,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
* @since GemFire 5.9
*/
@Override
- public Set getBucketOwners() {
+ public Set<InternalDistributedMember> getBucketOwners() {
return getBucketAdvisor().getProxyBucketRegion().getBucketOwners();
}
@@ -2072,20 +1988,20 @@ public class BucketRegion extends DistributedRegion implements Bucket {
this.counter = counter;
}
- public void updateCounter(long delta) {
+ void updateCounter(long delta) {
if (delta != 0) {
- this.counter.getAndAdd(delta);
+ counter.getAndAdd(delta);
}
}
public void resetCounter() {
- if (this.counter.get() != 0) {
- this.counter.set(0);
+ if (counter.get() != 0) {
+ counter.set(0);
}
}
public long getLimit() {
- if (this.limit == null) {
+ if (limit == null) {
return 0;
}
return limit.get();
@@ -2099,7 +2015,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
this.limit.set(limit);
}
- static int calcMemSize(Object value) {
+ private static int calcMemSize(Object value) {
if (value == null || value instanceof Token) {
return 0;
}
@@ -2129,19 +2045,19 @@ public class BucketRegion extends DistributedRegion implements Bucket {
// a destroy could have already been applied to the map, and then updates
// the stat after we reset it, making the state negative.
- final PartitionedRegionDataStore prDs = this.partitionedRegion.getDataStore();
+ final PartitionedRegionDataStore prDs = partitionedRegion.getDataStore();
long oldMemValue;
- if (this.isDestroyed || this.isDestroyingDiskRegion) {
+ if (isDestroyed || isDestroyingDiskRegion) {
// If this region is destroyed, mark the stat as destroyed.
- oldMemValue = this.bytesInMemory.getAndSet(BUCKET_DESTROYED);
+ oldMemValue = bytesInMemory.getAndSet(BUCKET_DESTROYED);
- } else if (!this.isInitialized()) {
+ } else if (!isInitialized()) {
// This case is rather special. We clear the region if the GII failed.
// In the case of bucket regions, we know that there will be no concurrent operations
// if GII has failed, because there is not primary. So it's safe to set these
// counters to 0.
- oldMemValue = this.bytesInMemory.getAndSet(0);
+ oldMemValue = bytesInMemory.getAndSet(0);
}
else {
@@ -2149,7 +2065,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
"Trying to clear a bucket region that was not destroyed or in initialization.");
}
if (oldMemValue != BUCKET_DESTROYED) {
- this.partitionedRegion.getPrStats().incDataStoreEntryCount(-sizeBeforeClear);
+ partitionedRegion.getPrStats().incDataStoreEntryCount(-sizeBeforeClear);
prDs.updateMemoryStats(-oldMemValue);
}
}
@@ -2172,21 +2088,20 @@ public class BucketRegion extends DistributedRegion implements Bucket {
@Override
public void updateSizeOnCreate(Object key, int newSize) {
- this.partitionedRegion.getPrStats().incDataStoreEntryCount(1);
+ partitionedRegion.getPrStats().incDataStoreEntryCount(1);
updateBucket2Size(0, newSize, SizeOp.CREATE);
}
@Override
public void updateSizeOnRemove(Object key, int oldSize) {
- this.partitionedRegion.getPrStats().incDataStoreEntryCount(-1);
+ partitionedRegion.getPrStats().incDataStoreEntryCount(-1);
updateBucket2Size(oldSize, 0, SizeOp.DESTROY);
}
@Override
public int updateSizeOnEvict(Object key, int oldSize) {
- int newDiskSize = oldSize;
- updateBucket2Size(oldSize, newDiskSize, SizeOp.EVICT);
- return newDiskSize;
+ updateBucket2Size(oldSize, oldSize, SizeOp.EVICT);
+ return oldSize;
}
@Override
@@ -2227,7 +2142,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
public long getTotalBytes() {
- long result = this.bytesInMemory.get();
+ long result = bytesInMemory.get();
if (result == BUCKET_DESTROYED) {
return 0;
}
@@ -2236,7 +2151,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
public long getBytesInMemory() {
- long result = this.bytesInMemory.get();
+ long result = bytesInMemory.get();
if (result == BUCKET_DESTROYED) {
return 0;
}
@@ -2245,34 +2160,32 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
- public void preDestroyBucket(int bucketId) {}
+ void preDestroyBucket(int bucketId) {}
@Override
public void cleanupFailedInitialization() {
- this.preDestroyBucket(this.getId());
+ preDestroyBucket(getId());
super.cleanupFailedInitialization();
}
- protected void invokePartitionListenerAfterBucketRemoved() {
+ void invokePartitionListenerAfterBucketRemoved() {
PartitionListener[] partitionListeners = getPartitionedRegion().getPartitionListeners();
if (partitionListeners == null || partitionListeners.length == 0) {
return;
}
- for (int i = 0; i < partitionListeners.length; i++) {
- PartitionListener listener = partitionListeners[i];
+ for (PartitionListener listener : partitionListeners) {
if (listener != null) {
listener.afterBucketRemoved(getId(), keySet());
}
}
}
- protected void invokePartitionListenerAfterBucketCreated() {
+ void invokePartitionListenerAfterBucketCreated() {
PartitionListener[] partitionListeners = getPartitionedRegion().getPartitionListeners();
if (partitionListeners == null || partitionListeners.length == 0) {
return;
}
- for (int i = 0; i < partitionListeners.length; i++) {
- PartitionListener listener = partitionListeners[i];
+ for (PartitionListener listener : partitionListeners) {
if (listener != null) {
listener.afterBucketCreated(getId(), keySet());
}
@@ -2303,7 +2216,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
/**
* Updates the bucket size.
*/
- void updateBucket2Size(int oldSize, int newSize, SizeOp op) {
+ private void updateBucket2Size(int oldSize, int newSize, SizeOp op) {
final int memoryDelta = op.computeMemoryDelta(oldSize, newSize);
@@ -2313,7 +2226,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
updateBucketMemoryStats(memoryDelta);
}
- void updateBucketMemoryStats(final int memoryDelta) {
+ private void updateBucketMemoryStats(final int memoryDelta) {
if (memoryDelta != 0) {
final long bSize = bytesInMemory.compareAddAndGet(BUCKET_DESTROYED, memoryDelta);
@@ -2327,7 +2240,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
}
- final PartitionedRegionDataStore prDS = this.partitionedRegion.getDataStore();
+ final PartitionedRegionDataStore prDS = partitionedRegion.getDataStore();
prDS.updateMemoryStats(memoryDelta);
}
@@ -2336,11 +2249,11 @@ public class BucketRegion extends DistributedRegion implements Bucket {
* bucket.This value will decrease when a value is faulted in.
*/
public long getNumOverflowOnDisk() {
- return this.numOverflowOnDisk.get();
+ return numOverflowOnDisk.get();
}
public long getNumOverflowBytesOnDisk() {
- return this.numOverflowBytesOnDisk.get();
+ return numOverflowBytesOnDisk.get();
}
/**
@@ -2348,7 +2261,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
* will decrease when the entry is overflowed to disk.
*/
public long getNumEntriesInVM() {
- return this.numEntriesInVM.get();
+ return numEntriesInVM.get();
}
/**
@@ -2356,13 +2269,13 @@ public class BucketRegion extends DistributedRegion implements Bucket {
* bucket, by a given amount.
*/
public void incNumOverflowOnDisk(long delta) {
- this.numOverflowOnDisk.addAndGet(delta);
+ numOverflowOnDisk.addAndGet(delta);
}
public void incNumOverflowBytesOnDisk(long delta) {
if (delta == 0)
return;
- this.numOverflowBytesOnDisk.addAndGet(delta);
+ numOverflowBytesOnDisk.addAndGet(delta);
// The following could be reenabled at a future time.
// I deadcoded for now to make sure I didn't have it break
// the last 6.5 regression.
@@ -2379,16 +2292,16 @@ public class BucketRegion extends DistributedRegion implements Bucket {
* bucket,by a given amount.
*/
public void incNumEntriesInVM(long delta) {
- this.numEntriesInVM.addAndGet(delta);
+ numEntriesInVM.addAndGet(delta);
}
@Override
void incBucketEvictions() {
- this.evictions.getAndAdd(1);
+ evictions.getAndAdd(1);
}
public long getBucketEvictions() {
- return this.evictions.get();
+ return evictions.get();
}
@Override
@@ -2397,16 +2310,14 @@ public class BucketRegion extends DistributedRegion implements Bucket {
}
public int getSizeForEviction() {
- EvictionAttributes ea = this.getAttributes().getEvictionAttributes();
+ EvictionAttributes ea = getAttributes().getEvictionAttributes();
if (ea == null)
return 0;
EvictionAlgorithm algo = ea.getAlgorithm();
if (!algo.isLRUHeap())
return 0;
EvictionAction action = ea.getAction();
- int size =
- action.isLocalDestroy() ? this.getRegionMap().sizeInVM() : (int) this.getNumEntriesInVM();
- return size;
+ return action.isLocalDestroy() ? getRegionMap().sizeInVM() : (int) getNumEntriesInVM();
}
@Override
@@ -2416,17 +2327,17 @@ public class BucketRegion extends DistributedRegion implements Bucket {
@Override
public FilterProfile getFilterProfile() {
- return this.partitionedRegion.getFilterProfile();
+ return partitionedRegion.getFilterProfile();
}
@Override
public void setCloningEnabled(boolean isCloningEnabled) {
- this.partitionedRegion.setCloningEnabled(isCloningEnabled);
+ partitionedRegion.setCloningEnabled(isCloningEnabled);
}
@Override
public boolean getCloningEnabled() {
- return this.partitionedRegion.getCloningEnabled();
+ return partitionedRegion.getCloningEnabled();
}
@Override
@@ -2445,30 +2356,13 @@ public class BucketRegion extends DistributedRegion implements Bucket {
/**
* Invoked when a primary bucket is demoted.
*/
- public void beforeReleasingPrimaryLockDuringDemotion() {}
+ void beforeReleasingPrimaryLockDuringDemotion() {}
@Override
public RegionAttributes getAttributes() {
return this;
}
- public boolean areSecondariesPingable() {
-
- Set<InternalDistributedMember> hostingservers =
- this.partitionedRegion.getRegionAdvisor().getBucketOwners(this.getId());
- hostingservers.remove(cache.getDistributedSystem().getDistributedMember());
-
- if (cache.getLogger().fineEnabled())
- cache.getLogger()
- .fine("Pinging secondaries of bucket " + this.getId() + " on servers " + hostingservers);
-
- if (hostingservers.size() == 0)
- return true;
-
- return ServerPingMessage.send(cache, hostingservers);
-
- }
-
@Override
public boolean notifiesMultipleSerialGateways() {
return getPartitionedRegion().notifiesMultipleSerialGateways();
@@ -2494,7 +2388,7 @@ public class BucketRegion extends DistributedRegion implements Bucket {
@Override
protected void postDestroyRegion(boolean destroyDiskRegion, RegionEventImpl event) {
- DiskRegion dr = this.getDiskRegion();
+ DiskRegion dr = getDiskRegion();
if (dr != null && destroyDiskRegion) {
dr.statsClear(this);
}
@@ -2508,17 +2402,17 @@ public class BucketRegion extends DistributedRegion implements Bucket {
@Override
public String getNameForStats() {
- return this.getPartitionedRegion().getFullPath();
+ return getPartitionedRegion().getFullPath();
}
@Override
public void closeEntries() {
- this.entries.close(this);
+ entries.close(this);
}
@Override
public Set<VersionSource> clearEntries(RegionVersionVector rvv) {
- return this.entries.clear(rvv, this);
+ return entries.clear(rvv, this);
}
}
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/CacheDistributionAdvisor.java b/geode-core/src/main/java/org/apache/geode/internal/cache/CacheDistributionAdvisor.java
index eaf75c8..9e82a05 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/CacheDistributionAdvisor.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/CacheDistributionAdvisor.java
@@ -36,7 +36,6 @@ import org.apache.geode.cache.InterestPolicy;
import org.apache.geode.cache.RegionDestroyedException;
import org.apache.geode.cache.Scope;
import org.apache.geode.cache.SubscriptionAttributes;
-import org.apache.geode.distributed.Role;
import org.apache.geode.distributed.internal.ClusterDistributionManager;
import org.apache.geode.distributed.internal.DistributionAdvisor;
import org.apache.geode.distributed.internal.MembershipListener;
@@ -113,7 +112,7 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
super(region);
}
- public static CacheDistributionAdvisor createCacheDistributionAdvisor(
+ static CacheDistributionAdvisor createCacheDistributionAdvisor(
CacheDistributionAdvisee region) {
CacheDistributionAdvisor advisor = new CacheDistributionAdvisor(region);
advisor.initialize();
@@ -138,19 +137,16 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
*
* @param excludeInRecovery if true then members in recovery are excluded
*/
- private Set adviseAllEventsOrCached(final boolean excludeInRecovery)
+ private Set<InternalDistributedMember> adviseAllEventsOrCached(final boolean excludeInRecovery)
throws IllegalStateException {
getAdvisee().getCancelCriterion().checkCancelInProgress(null);
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- if (excludeInRecovery && cp.inRecovery) {
- return false;
- }
- return cp.cachedOrAllEventsWithListener();
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile cp = (CacheProfile) profile;
+ if (excludeInRecovery && cp.inRecovery) {
+ return false;
}
+ return cp.cachedOrAllEventsWithListener();
});
}
@@ -166,15 +162,12 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
// The new value is null so this is a create with a null value,
// in which case we only need to distribute this message to replicates
// or all events that are not a proxy or if a proxy has a listener
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- DataPolicy dp = cp.dataPolicy;
- return dp.withReplication()
- || (cp.allEvents() && (dp.withStorage() || cp.hasCacheListener));
- }
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile cp = (CacheProfile) profile;
+ DataPolicy dp = cp.dataPolicy;
+ return dp.withReplication()
+ || (cp.allEvents() && (dp.withStorage() || cp.hasCacheListener));
});
}
}
@@ -186,33 +179,27 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
* Currently this is any other member who has this region defined. No reference to Set
* kept by advisor so caller is free to modify it
*/
- public Set<InternalDistributedMember> adviseTX() throws IllegalStateException {
+ Set<InternalDistributedMember> adviseTX() throws IllegalStateException {
boolean isMetaDataWithTransactions = getAdvisee() instanceof LocalRegion
&& ((LocalRegion) getAdvisee()).isMetaRegionWithTransactions();
Set<InternalDistributedMember> badList = Collections.emptySet();
if (!TXManagerImpl.ALLOW_PERSISTENT_TRANSACTIONS && !isMetaDataWithTransactions) {
- badList = adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile prof = (CacheProfile) profile;
- return (prof.isPersistent());
- }
+ badList = adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile prof = (CacheProfile) profile;
+ return (prof.isPersistent());
});
}
if (badList.isEmpty()) {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- return cp.cachedOrAllEvents();
- }
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile cp = (CacheProfile) profile;
+ return cp.cachedOrAllEvents();
});
} else {
- StringBuffer badIds = new StringBuffer();
+ StringBuilder badIds = new StringBuilder();
Iterator biI = badList.iterator();
while (biI.hasNext()) {
badIds.append(biI.next().toString());
@@ -232,26 +219,23 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
* by advisor so caller is free to modify it
*/
public Set adviseNetLoad() {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile prof = (CacheProfile) profile;
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile prof = (CacheProfile) profile;
- // if region in cache is not yet initialized, exclude
- if (!prof.regionInitialized) { // fix for bug 41102
- return false;
- }
-
- return prof.hasCacheLoader;
+ // if region in cache is not yet initialized, exclude
+ if (!prof.regionInitialized) { // fix for bug 41102
+ return false;
}
+
+ return prof.hasCacheLoader;
});
}
public FilterRoutingInfo adviseFilterRouting(CacheEvent event, Set cacheOpRecipients) {
FilterProfile fp = ((LocalRegion) event.getRegion()).getFilterProfile();
if (fp != null) {
- return fp.getFilterRoutingInfoPart1(event, this.profiles, cacheOpRecipients);
+ return fp.getFilterRoutingInfoPart1(event, profiles, cacheOpRecipients);
}
return null;
}
@@ -260,45 +244,18 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
/**
* Same as adviseGeneric except in recovery excluded.
*/
- public Set adviseCacheOp() {
+ public Set<InternalDistributedMember> adviseCacheOp() {
return adviseAllEventsOrCached(true);
}
- /**
- * Same as adviseCacheOp but only includes members that are playing the specified role.
- *
- * @since GemFire 5.0
- */
- public Set adviseCacheOpRole(final Role role) {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- // if region in cache is not yet initialized, exclude
- if (!cp.regionInitialized) {
- return false;
- }
- if (!cp.cachedOrAllEventsWithListener()) {
- return false;
- }
- return cp.getDistributedMember().getRoles().contains(role);
- }
- });
- }
-
-
/*
* * Same as adviseGeneric but excludes if cache profile is in recovery
*/
- public Set adviseInvalidateRegion() {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- return !cp.inRecovery;
- }
+ Set<InternalDistributedMember> adviseInvalidateRegion() {
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile cp = (CacheProfile) profile;
+ return !cp.inRecovery;
});
}
@@ -317,32 +274,23 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
* kept by advisor so caller is free to modify it
*/
public Set adviseNetWrite() {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile prof = (CacheProfile) profile;
- // if region in cache is in recovery, exclude
- if (prof.inRecovery) {
- return false;
- }
-
- return prof.hasCacheWriter;
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile prof = (CacheProfile) profile;
+ // if region in cache is in recovery, exclude
+ if (prof.inRecovery) {
+ return false;
}
+
+ return prof.hasCacheWriter;
});
}
public Set<InternalDistributedMember> adviseInitializedReplicates() {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- if (cp.dataPolicy.withReplication() && cp.regionInitialized) {
- return true;
- }
- return false;
- }
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile cp = (CacheProfile) profile;
+ return cp.dataPolicy.withReplication() && cp.regionInitialized;
});
}
@@ -352,19 +300,16 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
* @return Set of Serializable member ids that have the region and are have storage (no need to
* search an empty cache)
*/
- public Set adviseNetSearch() {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- // if region in cache is not yet initialized, exclude
- if (!cp.regionInitialized) {
- return false;
- }
- DataPolicy dp = cp.dataPolicy;
- return dp.withStorage();
+ Set adviseNetSearch() {
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile cp = (CacheProfile) profile;
+ // if region in cache is not yet initialized, exclude
+ if (!cp.regionInitialized) {
+ return false;
}
+ DataPolicy dp = cp.dataPolicy;
+ return dp.withStorage();
});
}
@@ -383,23 +328,23 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
dumpProfiles("AdviseInitialImage");
}
- Profile[] allProfiles = this.profiles; // volatile read
+ Profile[] allProfiles = profiles; // volatile read
if (allProfiles.length == 0) {
return new InitialImageAdvice();
}
- Set<InternalDistributedMember> replicates = new HashSet<InternalDistributedMember>();
- Set<InternalDistributedMember> others = new HashSet<InternalDistributedMember>();
- Set<InternalDistributedMember> preloaded = new HashSet<InternalDistributedMember>();
- Set<InternalDistributedMember> empties = new HashSet<InternalDistributedMember>();
- Set<InternalDistributedMember> uninitialized = new HashSet<InternalDistributedMember>();
- Set<InternalDistributedMember> nonPersistent = new HashSet<InternalDistributedMember>();
+ Set<InternalDistributedMember> replicates = new HashSet<>();
+ Set<InternalDistributedMember> others = new HashSet<>();
+ Set<InternalDistributedMember> preloaded = new HashSet<>();
+ Set<InternalDistributedMember> empties = new HashSet<>();
+ Set<InternalDistributedMember> uninitialized = new HashSet<>();
+ Set<InternalDistributedMember> nonPersistent = new HashSet<>();
Map<InternalDistributedMember, CacheProfile> memberProfiles =
- new HashMap<InternalDistributedMember, CacheProfile>();
+ new HashMap<>();
- for (int i = 0; i < allProfiles.length; i++) {
- CacheProfile profile = (CacheProfile) allProfiles[i];
+ for (Profile allProfile : allProfiles) {
+ CacheProfile profile = (CacheProfile) allProfile;
// Make sure that we don't return a member that was in the previous initial image advice.
// Unless that member has changed it's profile since the last time we checked.
@@ -460,14 +405,11 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
*
* @since GemFire 5.5
*/
- public Set adviseRequiresOldValueInCacheOp() {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- return cp.requiresOldValueInEvents && !cp.regionInitialized;
- }
+ Set adviseRequiresOldValueInCacheOp() {
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile cp = (CacheProfile) profile;
+ return cp.requiresOldValueInEvents && !cp.regionInitialized;
});
}
@@ -538,7 +480,7 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
/**
* Some cache listeners require old values in cache operation messages, at least during GII
*/
- public boolean requiresOldValueInEvents;
+ boolean requiresOldValueInEvents;
/**
* Whether the region has completed initialization, including GII. This information may be
@@ -567,14 +509,14 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
*/
public boolean hasCacheServer = false;
- public List<CacheServiceProfile> cacheServiceProfiles = new ArrayList<>();
+ List<CacheServiceProfile> cacheServiceProfiles = new ArrayList<>();
/** for internal use, required for DataSerializer.readObject */
public CacheProfile() {}
/** used for routing computation */
public CacheProfile(FilterProfile localProfile) {
- this.filterProfile = localProfile;
+ filterProfile = localProfile;
}
public CacheProfile(InternalDistributedMember memberId, int version) {
@@ -589,58 +531,58 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
/** Return the profile data information that can be stored in an int */
protected int getIntInfo() {
int s = 0;
- if (this.dataPolicy.withReplication()) {
+ if (dataPolicy.withReplication()) {
s |= REPLICATE_MASK;
- if (this.dataPolicy.isPersistentReplicate()) {
+ if (dataPolicy.isPersistentReplicate()) {
s |= PERSISTENT_MASK;
}
} else {
- if (this.dataPolicy.isEmpty())
+ if (dataPolicy.isEmpty())
s |= PROXY_MASK;
- if (this.dataPolicy.isPreloaded())
+ if (dataPolicy.isPreloaded())
s |= PRELOADED_MASK;
}
- if (this.subscriptionAttributes != null
- && this.subscriptionAttributes.getInterestPolicy().isAll()) {
+ if (subscriptionAttributes != null
+ && subscriptionAttributes.getInterestPolicy().isAll()) {
s |= INTEREST_MASK;
}
- if (this.hasCacheLoader)
+ if (hasCacheLoader)
s |= LOADER_MASK;
- if (this.hasCacheWriter)
+ if (hasCacheWriter)
s |= WRITER_MASK;
- if (this.hasCacheListener)
+ if (hasCacheListener)
s |= LISTENER_MASK;
- if (this.scope.isDistributedAck())
+ if (scope.isDistributedAck())
s |= DIST_ACK_MASK;
- if (this.scope.isGlobal())
+ if (scope.isGlobal())
s |= GLOBAL_MASK;
- if (this.inRecovery)
+ if (inRecovery)
s |= IN_RECOVERY_MASK;
- if (this.isPartitioned)
+ if (isPartitioned)
s |= IS_PARTITIONED_MASK;
- if (this.isGatewayEnabled)
+ if (isGatewayEnabled)
s |= IS_GATEWAY_ENABLED_MASK;
- if (this.isPersistent)
+ if (isPersistent)
s |= PERSISTENT_MASK;
- if (this.regionInitialized)
+ if (regionInitialized)
s |= REGION_INITIALIZED_MASK;
- if (this.persistentID != null)
+ if (persistentID != null)
s |= PERSISTENT_ID_MASK;
- if (this.hasCacheServer)
+ if (hasCacheServer)
s |= HAS_CACHE_SERVER_MASK;
- if (this.requiresOldValueInEvents)
+ if (requiresOldValueInEvents)
s |= REQUIRES_OLD_VALUE_MASK;
- if (this.persistenceInitialized)
+ if (persistenceInitialized)
s |= PERSISTENCE_INITIALIZED_MASK;
- if (!this.gatewaySenderIds.isEmpty())
+ if (!gatewaySenderIds.isEmpty())
s |= GATEWAY_SENDER_IDS_MASK;
- if (!this.asyncEventQueueIds.isEmpty())
+ if (!asyncEventQueueIds.isEmpty())
s |= ASYNC_EVENT_QUEUE_IDS_MASK;
- if (this.isOffHeap)
+ if (isOffHeap)
s |= IS_OFF_HEAP_MASK;
- if (!this.cacheServiceProfiles.isEmpty())
+ if (!cacheServiceProfiles.isEmpty())
s |= CACHE_SERVICE_PROFILES_MASK;
- Assert.assertTrue(!this.scope.isLocal());
+ Assert.assertTrue(!scope.isLocal());
return s;
}
@@ -660,52 +602,52 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
}
public boolean isPersistent() {
- return this.dataPolicy.withPersistence();
+ return dataPolicy.withPersistence();
}
/** Set the profile data information that is stored in a short */
protected void setIntInfo(int s) {
if ((s & REPLICATE_MASK) != 0) {
if ((s & PERSISTENT_MASK) != 0) {
- this.dataPolicy = DataPolicy.PERSISTENT_REPLICATE;
+ dataPolicy = DataPolicy.PERSISTENT_REPLICATE;
} else {
- this.dataPolicy = DataPolicy.REPLICATE;
+ dataPolicy = DataPolicy.REPLICATE;
}
} else if ((s & PROXY_MASK) != 0) {
- this.dataPolicy = DataPolicy.EMPTY;
+ dataPolicy = DataPolicy.EMPTY;
} else if ((s & PRELOADED_MASK) != 0) {
- this.dataPolicy = DataPolicy.PRELOADED;
+ dataPolicy = DataPolicy.PRELOADED;
} else { // CACHED
- this.dataPolicy = DataPolicy.NORMAL;
+ dataPolicy = DataPolicy.NORMAL;
}
if ((s & IS_PARTITIONED_MASK) != 0) {
if ((s & PERSISTENT_MASK) != 0) {
- this.dataPolicy = DataPolicy.PERSISTENT_PARTITION;
+ dataPolicy = DataPolicy.PERSISTENT_PARTITION;
} else {
- this.dataPolicy = DataPolicy.PARTITION;
+ dataPolicy = DataPolicy.PARTITION;
}
}
if ((s & INTEREST_MASK) != 0) {
- this.subscriptionAttributes = new SubscriptionAttributes(InterestPolicy.ALL);
+ subscriptionAttributes = new SubscriptionAttributes(InterestPolicy.ALL);
} else {
- this.subscriptionAttributes = new SubscriptionAttributes(InterestPolicy.CACHE_CONTENT);
+ subscriptionAttributes = new SubscriptionAttributes(InterestPolicy.CACHE_CONTENT);
}
- this.hasCacheLoader = (s & LOADER_MASK) != 0;
- this.hasCacheWriter = (s & WRITER_MASK) != 0;
- this.hasCacheListener = (s & LISTENER_MASK) != 0;
- this.scope = (s & DIST_ACK_MASK) != 0 ? Scope.DISTRIBUTED_ACK
+ hasCacheLoader = (s & LOADER_MASK) != 0;
+ hasCacheWriter = (s & WRITER_MASK) != 0;
+ hasCacheListener = (s & LISTENER_MASK) != 0;
+ scope = (s & DIST_ACK_MASK) != 0 ? Scope.DISTRIBUTED_ACK
: ((s & GLOBAL_MASK) != 0 ? Scope.GLOBAL : Scope.DISTRIBUTED_NO_ACK);
- this.inRecovery = (s & IN_RECOVERY_MASK) != 0;
- this.isPartitioned = (s & IS_PARTITIONED_MASK) != 0;
- this.isGatewayEnabled = (s & IS_GATEWAY_ENABLED_MASK) != 0;
- this.isPersistent = (s & PERSISTENT_MASK) != 0;
- this.regionInitialized = ((s & REGION_INITIALIZED_MASK) != 0);
- this.hasCacheServer = ((s & HAS_CACHE_SERVER_MASK) != 0);
- this.requiresOldValueInEvents = ((s & REQUIRES_OLD_VALUE_MASK) != 0);
- this.persistenceInitialized = (s & PERSISTENCE_INITIALIZED_MASK) != 0;
- this.isOffHeap = (s & IS_OFF_HEAP_MASK) != 0;
+ inRecovery = (s & IN_RECOVERY_MASK) != 0;
+ isPartitioned = (s & IS_PARTITIONED_MASK) != 0;
+ isGatewayEnabled = (s & IS_GATEWAY_ENABLED_MASK) != 0;
+ isPersistent = (s & PERSISTENT_MASK) != 0;
+ regionInitialized = ((s & REGION_INITIALIZED_MASK) != 0);
+ hasCacheServer = ((s & HAS_CACHE_SERVER_MASK) != 0);
+ requiresOldValueInEvents = ((s & REQUIRES_OLD_VALUE_MASK) != 0);
+ persistenceInitialized = (s & PERSISTENCE_INITIALIZED_MASK) != 0;
+ isOffHeap = (s & IS_OFF_HEAP_MASK) != 0;
}
/**
@@ -714,13 +656,13 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
* @since GemFire 5.0
*/
public void setSubscriptionAttributes(SubscriptionAttributes sa) {
- this.subscriptionAttributes = sa;
+ subscriptionAttributes = sa;
}
/**
* Return true if cached or allEvents and a listener
*/
- public boolean cachedOrAllEventsWithListener() {
+ boolean cachedOrAllEventsWithListener() {
// to fix bug 36804 to ignore hasCacheListener
// return this.dataPolicy.withStorage() ||
// (allEvents() && this.hasCacheListener);
@@ -730,19 +672,19 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
/**
* Return true if cached or allEvents
*/
- public boolean cachedOrAllEvents() {
- return this.dataPolicy.withStorage() || allEvents();
+ boolean cachedOrAllEvents() {
+ return dataPolicy.withStorage() || allEvents();
}
/**
* Return true if subscribed to all events
*/
- public boolean allEvents() {
- return this.subscriptionAttributes.getInterestPolicy().isAll();
+ boolean allEvents() {
+ return subscriptionAttributes.getInterestPolicy().isAll();
}
public void addCacheServiceProfile(CacheServiceProfile profile) {
- this.cacheServiceProfiles.add(profile);
+ cacheServiceProfiles.add(profile);
}
private boolean hasCacheServiceProfiles(int bits) {
@@ -800,8 +742,8 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
@Override
public void cleanUp() {
- if (this.filterProfile != null) {
- this.filterProfile.cleanUp();
+ if (filterProfile != null) {
+ filterProfile.cleanUp();
}
}
@@ -846,7 +788,7 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
if (!asyncEventQueueIds.isEmpty()) {
writeSet(asyncEventQueueIds, out);
}
- DataSerializer.writeObject(this.filterProfile, out);
+ DataSerializer.writeObject(filterProfile, out);
if (!cacheServiceProfiles.isEmpty()) {
DataSerializer.writeObject(cacheServiceProfiles, out);
}
@@ -873,7 +815,7 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
if (hasAsyncEventQueueIds(bits)) {
asyncEventQueueIds = DataSerializer.readObject(in);
}
- this.filterProfile = DataSerializer.readObject(in);
+ filterProfile = DataSerializer.readObject(in);
if (hasCacheServiceProfiles(bits)) {
cacheServiceProfiles = DataSerializer.readObject(in);
}
@@ -887,33 +829,33 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
@Override
public void fillInToString(StringBuilder sb) {
super.fillInToString(sb);
- sb.append("; dataPolicy=" + this.dataPolicy);
- sb.append("; hasCacheLoader=" + this.hasCacheLoader);
- sb.append("; hasCacheWriter=" + this.hasCacheWriter);
- sb.append("; hasCacheListener=" + this.hasCacheListener);
- sb.append("; hasCacheServer=").append(this.hasCacheServer);
- sb.append("; scope=" + this.scope);
- sb.append("; regionInitialized=").append(String.valueOf(this.regionInitialized));
- sb.append("; inRecovery=" + this.inRecovery);
- sb.append("; subcription=" + this.subscriptionAttributes);
- sb.append("; isPartitioned=" + this.isPartitioned);
- sb.append("; isGatewayEnabled=" + this.isGatewayEnabled);
- sb.append("; isPersistent=" + this.isPersistent);
- sb.append("; persistentID=" + this.persistentID);
- if (this.filterProfile != null) {
- sb.append("; ").append(this.filterProfile);
+ sb.append("; dataPolicy=").append(dataPolicy);
+ sb.append("; hasCacheLoader=").append(hasCacheLoader);
+ sb.append("; hasCacheWriter=").append(hasCacheWriter);
+ sb.append("; hasCacheListener=").append(hasCacheListener);
+ sb.append("; hasCacheServer=").append(hasCacheServer);
+ sb.append("; scope=").append(scope);
+ sb.append("; regionInitialized=").append(regionInitialized);
+ sb.append("; inRecovery=").append(inRecovery);
+ sb.append("; subcription=").append(subscriptionAttributes);
+ sb.append("; isPartitioned=").append(isPartitioned);
+ sb.append("; isGatewayEnabled=").append(isGatewayEnabled);
+ sb.append("; isPersistent=").append(isPersistent);
+ sb.append("; persistentID=").append(persistentID);
+ if (filterProfile != null) {
+ sb.append("; ").append(filterProfile);
}
- sb.append("; gatewaySenderIds =" + this.gatewaySenderIds);
- sb.append("; asyncEventQueueIds =" + this.asyncEventQueueIds);
- sb.append("; IsOffHeap=" + this.isOffHeap);
- sb.append("; cacheServiceProfiles=" + this.cacheServiceProfiles);
+ sb.append("; gatewaySenderIds =").append(gatewaySenderIds);
+ sb.append("; asyncEventQueueIds =").append(asyncEventQueueIds);
+ sb.append("; IsOffHeap=").append(isOffHeap);
+ sb.append("; cacheServiceProfiles=").append(cacheServiceProfiles);
}
}
/** Recipient information used for getInitialImage operation */
public static class InitialImageAdvice {
public Set<InternalDistributedMember> getOthers() {
- return this.others;
+ return others;
}
public void setOthers(Set<InternalDistributedMember> others) {
@@ -921,23 +863,23 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
}
public Set<InternalDistributedMember> getReplicates() {
- return this.replicates;
+ return replicates;
}
public Set<InternalDistributedMember> getNonPersistent() {
- return this.nonPersistent;
+ return nonPersistent;
}
public Set<InternalDistributedMember> getPreloaded() {
- return this.preloaded;
+ return preloaded;
}
public Set<InternalDistributedMember> getEmpties() {
- return this.empties;
+ return empties;
}
public Set<InternalDistributedMember> getUninitialized() {
- return this.uninitialized;
+ return uninitialized;
}
/** Set of replicate recipients */
@@ -960,7 +902,7 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
protected final Set<InternalDistributedMember> uninitialized;
/** Set of members that are replicates but not persistent */
- protected final Set<InternalDistributedMember> nonPersistent;
+ final Set<InternalDistributedMember> nonPersistent;
private final Map<InternalDistributedMember, CacheProfile> memberProfiles;
@@ -980,58 +922,20 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
}
public InitialImageAdvice() {
- this(Collections.EMPTY_SET, Collections.EMPTY_SET, Collections.EMPTY_SET,
- Collections.EMPTY_SET, Collections.EMPTY_SET, Collections.EMPTY_SET,
- Collections.<InternalDistributedMember, CacheProfile>emptyMap());
+ this(Collections.emptySet(), Collections.emptySet(), Collections.emptySet(),
+ Collections.emptySet(), Collections.emptySet(), Collections.emptySet(),
+ Collections.emptyMap());
}
@Override
public String toString() {
- return "InitialImageAdvice(" + "replicates=" + this.replicates + "; others=" + this.others
- + "; preloaded=" + this.preloaded + "; empty=" + this.empties + "; initializing="
- + this.uninitialized + ")";
+ return "InitialImageAdvice(" + "replicates=" + replicates + "; others=" + others
+ + "; preloaded=" + preloaded + "; empty=" + empties + "; initializing="
+ + uninitialized + ")";
}
}
- // moved putProfile, doPutProfile, and putProfile to DistributionAdvisor
-
- // moved isNewerProfile to DistributionAdvisor
-
- // moved isNewerSerialNumber to DistributionAdvisor
-
- // moved forceNewMembershipVersion to DistributionAdvisor
-
- // moved startOperation to DistributionAdvisor
-
- // moved endOperation to DistributionAdvisor
-
- /**
- * Provide only the new replicates given a set of existing memberIds
- *
- * @param oldRecipients the <code>Set</code> of memberIds that have received the message
- * @return the set of new replicate's memberIds
- * @since GemFire 5.1
- */
- public Set adviseNewReplicates(final Set oldRecipients) {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- if (cp.dataPolicy.withReplication() && !oldRecipients.contains(cp.getDistributedMember())) {
- return true;
- }
- return false;
- }
- });
- }
-
- // moved waitForCurrentOperations to DistributionAdvisor
-
- // moved removeId, doRemoveId, removeIdWithSerial, and updateRemovedProfiles to
- // DistributionAdvisor
-
/**
* Provide all the replicates including persistent replicates.
*
@@ -1039,16 +943,10 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
* @since GemFire 5.8
*/
public Set<InternalDistributedMember> adviseReplicates() {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- if (cp.dataPolicy.withReplication()) {
- return true;
- }
- return false;
- }
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile cp = (CacheProfile) profile;
+ return cp.dataPolicy.withReplication();
});
}
@@ -1059,16 +957,10 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
* @since GemFire prPersistSprint1
*/
public Set advisePreloadeds() {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- if (cp.dataPolicy.withPreloaded()) {
- return true;
- }
- return false;
- }
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile cp = (CacheProfile) profile;
+ return cp.dataPolicy.withPreloaded();
});
}
@@ -1078,37 +970,11 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
* @return the set of replicate's memberIds
* @since GemFire 5.8
*/
- public Set adviseEmptys() {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- if (cp.dataPolicy.isEmpty()) {
- return true;
- }
- return false;
- }
- });
- }
-
- /**
- * Provide only the normals (having DataPolicy.NORMAL) given a set of existing memberIds
- *
- * @return the set of normal's memberIds
- * @since GemFire 5.8
- */
- public Set adviseNormals() {
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- if (cp.dataPolicy.isNormal()) {
- return true;
- }
- return false;
- }
+ Set adviseEmptys() {
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile cp = (CacheProfile) profile;
+ return cp.dataPolicy.isEmpty();
});
}
@@ -1130,8 +996,8 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
initializationGate();
Map<InternalDistributedMember, PersistentMemberID> result =
- new HashMap<InternalDistributedMember, PersistentMemberID>();
- Profile[] snapshot = this.profiles;
+ new HashMap<>();
+ Profile[] snapshot = profiles;
for (Profile profile : snapshot) {
CacheProfile cp = (CacheProfile) profile;
if (cp.persistentID != null) {
@@ -1146,8 +1012,8 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
initializationGate();
Map<InternalDistributedMember, PersistentMemberID> result =
- new HashMap<InternalDistributedMember, PersistentMemberID>();
- Profile[] snapshot = this.profiles;
+ new HashMap<>();
+ Profile[] snapshot = profiles;
for (Profile profile : snapshot) {
CacheProfile cp = (CacheProfile) profile;
if (cp.persistentID != null && cp.persistenceInitialized) {
@@ -1158,15 +1024,12 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
return result;
}
- public Set adviseCacheServers() {
+ Set adviseCacheServers() {
getAdvisee().getCancelCriterion().checkCancelInProgress(null);
- return adviseFilter(new Filter() {
- @Override
- public boolean include(Profile profile) {
- assert profile instanceof CacheProfile;
- CacheProfile cp = (CacheProfile) profile;
- return cp.hasCacheServer;
- }
+ return adviseFilter(profile -> {
+ assert profile instanceof CacheProfile;
+ CacheProfile cp = (CacheProfile) profile;
+ return cp.hasCacheServer;
});
}
@@ -1219,43 +1082,37 @@ public class CacheDistributionAdvisor extends DistributionAdvisor {
}
public List<Set<String>> adviseSameGatewaySenderIds(final Set<String> allGatewaySenderIds) {
- final List<Set<String>> differSenderIds = new ArrayList<Set<String>>();
- fetchProfiles(new Filter() {
- @Override
- public boolean include(final Profile profile) {
- if (profile instanceof CacheProfile) {
- final CacheProfile cp = (CacheProfile) profile;
- if (allGatewaySenderIds.equals(cp.gatewaySenderIds)) {
- return true;
- } else {
- differSenderIds.add(allGatewaySenderIds);
- differSenderIds.add(cp.gatewaySenderIds);
- return false;
- }
+ final List<Set<String>> differSenderIds = new ArrayList<>();
+ fetchProfiles(profile -> {
+ if (profile instanceof CacheProfile) {
+ final CacheProfile cp = (CacheProfile) profile;
+ if (allGatewaySenderIds.equals(cp.gatewaySenderIds)) {
+ return true;
+ } else {
+ differSenderIds.add(allGatewaySenderIds);
+ differSenderIds.add(cp.gatewaySenderIds);
+ return false;
}
- return false;
}
+ return false;
});
return differSenderIds;
}
public List<Set<String>> adviseSameAsyncEventQueueIds(final Set<String> allAsyncEventIds) {
- final List<Set<String>> differAsycnQueueIds = new ArrayList<Set<String>>();
- List l = fetchProfiles(new Filter() {
- @Override
- public boolean include(final Profile profile) {
- if (profile instanceof CacheProfile) {
- final CacheProfile cp = (CacheProfile) profile;
- if (allAsyncEventIds.equals(cp.asyncEventQueueIds)) {
- return true;
- } else {
- differAsycnQueueIds.add(allAsyncEventIds);
- differAsycnQueueIds.add(cp.asyncEventQueueIds);
- return false;
- }
+ final List<Set<String>> differAsycnQueueIds = new ArrayList<>();
+ fetchProfiles(profile -> {
+ if (profile instanceof CacheProfile) {
+ final CacheProfile cp = (CacheProfile) profile;
+ if (allAsyncEventIds.equals(cp.asyncEventQueueIds)) {
+ return true;
+ } else {
+ differAsycnQueueIds.add(allAsyncEventIds);
+ differAsycnQueueIds.add(cp.asyncEventQueueIds);
+ return false;
}
- return false;
}
+ return false;
});
return differAsycnQueueIds;
}
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedRegion.java b/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedRegion.java
index 4f704a2..4f8ccfe 100755
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedRegion.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedRegion.java
@@ -12,6 +12,7 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
+
package org.apache.geode.internal.cache;
import java.io.IOException;
@@ -148,7 +149,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
final AdvisorListener advisorListener = new AdvisorListener();
/** Set of currently missing required roles */
- final HashSet missingRequiredRoles = new HashSet(); // package-private to avoid synthetic accessor
+ private final HashSet<Role> missingRequiredRoles = new HashSet<>();
/** True if this region is currently missing any required roles */
private volatile boolean isMissingRequiredRoles = false;
@@ -193,9 +194,9 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
protected DistributedRegion(String regionName, RegionAttributes attrs, LocalRegion parentRegion,
InternalCache cache, InternalRegionArguments internalRegionArgs) {
super(regionName, attrs, parentRegion, cache, internalRegionArgs);
- this.initializationLatchAfterMemberTimeout =
+ initializationLatchAfterMemberTimeout =
new StoppableCountDownLatch(getCancelCriterion(), 1);
- this.distAdvisor = createDistributionAdvisor(internalRegionArgs);
+ distAdvisor = createDistributionAdvisor(internalRegionArgs);
if (getDistributionManager().getConfig().getEnableNetworkPartitionDetection()
&& !isInternalRegion() && !attrs.getScope().isAck() && !doesNotDistribute()
@@ -221,16 +222,16 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
// immutable
// if this VM fulfills all required roles, make requiresReliabilityCheck
// false
- Set reqRoles = new HashSet(attrs.getMembershipAttributes().getRequiredRoles());
+ Set<Role> reqRoles = new HashSet<>(attrs.getMembershipAttributes().getRequiredRoles());
reqRoles.removeAll(getSystem().getDistributedMember().getRoles());
if (reqRoles.isEmpty()) {
setRequiresReliabilityCheck = false;
}
- this.requiresReliabilityCheck = setRequiresReliabilityCheck;
+ requiresReliabilityCheck = setRequiresReliabilityCheck;
if (internalRegionArgs.isUsedForPartitionedRegionBucket()) {
- this.persistenceAdvisor = internalRegionArgs.getPersistenceAdvisor();
+ persistenceAdvisor = internalRegionArgs.getPersistenceAdvisor();
} else if (allowsPersistence()) {
// TODO: prpersist - using this lock service is a hack. Maybe? Or maybe
// it's ok if we have one (rarely used) lock service for many operations?
@@ -249,18 +250,18 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
diskStats = null;
}
PersistentMemberManager memberManager = cache.getPersistentMemberManager();
- this.persistenceAdvisor = new PersistenceAdvisorImpl(this.distAdvisor, dl, storage,
- this.getFullPath(), diskStats, memberManager);
+ persistenceAdvisor = new PersistenceAdvisorImpl(distAdvisor, dl, storage,
+ getFullPath(), diskStats, memberManager);
} catch (Exception ignore) {
throw new InternalGemFireError("Couldn't recover persistence");
}
} else {
- this.persistenceAdvisor = null;
+ persistenceAdvisor = null;
}
- if (this.persistenceAdvisor != null) {
- this.persistentId = this.persistenceAdvisor.generatePersistentID();
+ if (persistenceAdvisor != null) {
+ persistentId = persistenceAdvisor.generatePersistentID();
} else {
- this.persistentId = null;
+ persistentId = null;
}
}
@@ -313,11 +314,11 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
return false;
}
// if we're not allowed to generate a version tag we need to send it to someone who can
- if (!this.generateVersionTag) {
+ if (!generateVersionTag) {
return true;
}
- return this.getConcurrencyChecksEnabled() && (getServerProxy() == null) && !isTX()
- && this.scope.isDistributed() && !this.getDataPolicy().withReplication();
+ return getConcurrencyChecksEnabled() && (getServerProxy() == null) && !isTX()
+ && scope.isDistributed() && !getDataPolicy().withReplication();
}
@@ -328,34 +329,34 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
final boolean isTraceEnabled = logger.isTraceEnabled();
Lock dlock = null;
- if (this.scope.isGlobal() && // lock only applies to global scope
+ if (scope.isGlobal() && // lock only applies to global scope
!event.isOriginRemote() && // only if operation originating locally
!event.isNetSearch() && // search and load processor handles own locking
!event.isNetLoad() &&
// @todo darrel/kirk: what about putAll?
!event.isLocalLoad() && !event.isSingleHopPutOp()) {
// Single Hop Op means dlock is already taken at origin node.
- dlock = this.getDistributedLockIfGlobal(event.getKey());
+ dlock = getDistributedLockIfGlobal(event.getKey());
}
if (isTraceEnabled) {
logger.trace("virtualPut invoked for event {}", event);
}
try {
if (!hasSeenEvent(event)) {
- if (this.requiresOneHopForMissingEntry(event)) {
+ if (requiresOneHopForMissingEntry(event)) {
// bug #45704: see if a one-hop must be done for this operation
RegionEntry re = getRegionEntry(event.getKey());
- if (re == null /* || re.isTombstone() */ || !this.generateVersionTag) {
- if (!event.isBulkOpInProgress() || this.getDataPolicy().withStorage()) {
+ if (re == null /* || re.isTombstone() */ || !generateVersionTag) {
+ if (!event.isBulkOpInProgress() || getDataPolicy().withStorage()) {
// putAll will send a single one-hop for empty regions. for other missing entries
// we need to get a valid version number before modifying the local cache
boolean didDistribute = RemotePutMessage.distribute(event, lastModified, false, false,
- expectedOldValue, requireOldValue, !this.generateVersionTag);
+ expectedOldValue, requireOldValue, !generateVersionTag);
if (!didDistribute && isTraceEnabled) {
logger.trace("Unable to perform one-hop messaging");
}
- if (!this.generateVersionTag && !didDistribute) {
+ if (!generateVersionTag && !didDistribute) {
throw new PersistentReplicatesOfflineException();
}
if (didDistribute) {
@@ -426,15 +427,15 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
if (isTraceEnabled) {
logger.trace("basicPutEntry invoked for event {}", event);
}
- if (this.requiresOneHopForMissingEntry(event)) {
+ if (requiresOneHopForMissingEntry(event)) {
// bug #45704: see if a one-hop must be done for this operation
RegionEntry re = getRegionEntry(event.getKey());
- if (re == null /* || re.isTombstone() */ || !this.generateVersionTag) {
+ if (re == null /* || re.isTombstone() */ || !generateVersionTag) {
final boolean ifNew = false;
final boolean ifOld = false;
boolean didDistribute = RemotePutMessage.distribute(event, lastModified, ifNew, ifOld, null,
- false, !this.generateVersionTag);
- if (!this.generateVersionTag && !didDistribute) {
+ false, !generateVersionTag);
+ if (!generateVersionTag && !didDistribute) {
throw new PersistentReplicatesOfflineException();
}
if (didDistribute && isTraceEnabled) {
@@ -497,7 +498,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
UpdateOperation op = new UpdateOperation(event, lastModified);
if (logger.isTraceEnabled()) {
logger.trace("distributing operation for event : {} : for region : {}", event,
- this.getName());
+ getName());
}
op.distribute();
}
@@ -506,7 +507,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
public boolean hasSeenEvent(EntryEventImpl event) {
- boolean isDuplicate = false;
+ boolean isDuplicate;
isDuplicate = getEventTracker().hasSeenEvent(event);
if (isDuplicate) {
@@ -544,7 +545,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
protected boolean getGenerateVersionTag() {
- return this.generateVersionTag;
+ return generateVersionTag;
}
@Override
@@ -552,10 +553,10 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
if (logger.isTraceEnabled()) {
logger.trace(
"shouldGenerateVersionTag this.generateVersionTag={} ccenabled={} dataPolicy={} event:{}",
- this.generateVersionTag, this.getConcurrencyChecksEnabled(), this.getDataPolicy(), event);
+ generateVersionTag, getConcurrencyChecksEnabled(), getDataPolicy(), event);
}
- if (!this.getConcurrencyChecksEnabled() || this.getDataPolicy() == DataPolicy.EMPTY
- || !this.generateVersionTag) {
+ if (!getConcurrencyChecksEnabled() || getDataPolicy() == DataPolicy.EMPTY
+ || !generateVersionTag) {
return false;
}
if (getServerProxy() != null) { // client
@@ -567,19 +568,16 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
if (event.getOperation().isLocal()) { // bug #45402 - localDestroy generated a version tag
return false;
}
- if (!event.isOriginRemote() && this.getDataPolicy().withReplication()) {
+ if (!event.isOriginRemote() && getDataPolicy().withReplication()) {
return true;
}
- if (!this.getDataPolicy().withReplication() && !this.getDataPolicy().withPersistence()) {
- if (!entry.getVersionStamp().hasValidVersion()) {
- // do not generate a version stamp in a region that has no replication if it's not based
- // on an existing version from a replicate region
- return false;
- }
- return true;
+ if (!getDataPolicy().withReplication() && !getDataPolicy().withPersistence()) {
+ // do not generate a version stamp in a region that has no replication if it's not based
+ // on an existing version from a replicate region
+ return entry.getVersionStamp().hasValidVersion();
}
if (!event.isOriginRemote() && event.getDistributedMember() != null) {
- if (!event.getDistributedMember().equals(this.getMyId())) {
+ if (!event.getDistributedMember().equals(getMyId())) {
return event.getVersionTag() == null; // one-hop remote message
}
}
@@ -593,12 +591,12 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
*/
@Override
protected void checkForNoAccess() {
- if (this.requiresReliabilityCheck && this.isMissingRequiredRoles) {
+ if (requiresReliabilityCheck && isMissingRequiredRoles) {
if (getMembershipAttributes().getLossAction().isNoAccess()) {
- synchronized (this.missingRequiredRoles) {
- if (!this.isMissingRequiredRoles)
+ synchronized (missingRequiredRoles) {
+ if (!isMissingRequiredRoles)
return;
- Set roles = Collections.unmodifiableSet(new HashSet(this.missingRequiredRoles));
+ Set<Role> roles = Collections.unmodifiableSet(new HashSet<>(missingRequiredRoles));
throw new RegionAccessException(
String.format(
"Operation is disallowed by LossAction %s because these required roles are missing: %s.",
@@ -618,13 +616,13 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
*/
@Override
public void checkForLimitedOrNoAccess() {
- if (this.requiresReliabilityCheck && this.isMissingRequiredRoles) {
+ if (requiresReliabilityCheck && isMissingRequiredRoles) {
if (getMembershipAttributes().getLossAction().isNoAccess()
|| getMembershipAttributes().getLossAction().isLimitedAccess()) {
- synchronized (this.missingRequiredRoles) {
- if (!this.isMissingRequiredRoles)
+ synchronized (missingRequiredRoles) {
+ if (!isMissingRequiredRoles)
return;
- Set roles = Collections.unmodifiableSet(new HashSet(this.missingRequiredRoles));
+ Set<Role> roles = Collections.unmodifiableSet(new HashSet<>(missingRequiredRoles));
Assert.assertTrue(!roles.isEmpty());
throw new RegionAccessException(
String.format(
@@ -644,10 +642,10 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
private void handleReliableDistribution(Set successfulRecipients, Set otherRecipients1,
Set otherRecipients2) {
- if (this.requiresReliabilityCheck) {
+ if (requiresReliabilityCheck) {
MembershipAttributes ra = getMembershipAttributes();
// determine the successful roles
- Set roles = new HashSet();
+ Set<Role> roles = new HashSet<>();
for (Object successfulRecipient : successfulRecipients) {
InternalDistributedMember mbr = (InternalDistributedMember) successfulRecipient;
if (mbr != null) {
@@ -667,7 +665,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
}
// determine the missing roles
- Set failedRoles = new HashSet(ra.getRequiredRoles());
+ Set<Role> failedRoles = new HashSet<>(ra.getRequiredRoles());
failedRoles.removeAll(roles);
if (failedRoles.isEmpty()) {
return;
@@ -692,7 +690,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
* @since GemFire 5.0
*/
boolean isNoDistributionOk() {
- if (this.requiresReliabilityCheck) {
+ if (requiresReliabilityCheck) {
MembershipAttributes ra = getMembershipAttributes();
Set<Role> failedRoles = ra.getRequiredRoles();
throw new RegionDistributionException(
@@ -720,7 +718,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
public boolean requiresReliabilityCheck() {
- return this.requiresReliabilityCheck;
+ return requiresReliabilityCheck;
}
/**
@@ -734,14 +732,12 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
*/
@Override
protected boolean isExpirationAllowed(ExpiryTask expiry) {
- if (this.requiresReliabilityCheck && this.isMissingRequiredRoles) {
+ if (requiresReliabilityCheck && isMissingRequiredRoles) {
if (getMembershipAttributes().getLossAction().isNoAccess()) {
return false;
}
- if (getMembershipAttributes().getLossAction().isLimitedAccess()
- && expiry.isDistributedAction()) {
- return false;
- }
+ return !getMembershipAttributes().getLossAction().isLimitedAccess()
+ || !expiry.isDistributedAction();
}
return true;
}
@@ -777,33 +773,30 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
private void asyncResumeReliability(final InternalDistributedMember id,
final Set newlyAcquiredRoles) throws RejectedExecutionException {
final ResumptionAction ra = getMembershipAttributes().getResumptionAction();
- getDistributionManager().getWaitingThreadPool().execute(new Runnable() {
- @Override
- public void run() {
- try {
- if (ra.isReinitialize()) {
- if (logger.isDebugEnabled()) {
- logger.debug("Reliability resumption for action of reinitialize");
- }
- if (!isDestroyed() && !cache.isClosed()) {
- RegionEventImpl event = new RegionEventImpl(DistributedRegion.this,
- Operation.REGION_REINITIALIZE, null, false, getMyId(), generateEventID());
- reinitialize(null, event);
- }
- synchronized (missingRequiredRoles) {
- // any number of threads may be waiting on missingRequiredRoles
- missingRequiredRoles.notifyAll();
- if (hasListener() && id != null) {
- // fire afterRoleGain event
- RoleEventImpl relEvent = new RoleEventImpl(DistributedRegion.this,
- Operation.REGION_CREATE, null, true, id, newlyAcquiredRoles);
- dispatchListenerEvent(EnumListenerEvent.AFTER_ROLE_GAIN, relEvent);
- }
+ getDistributionManager().getWaitingThreadPool().execute(() -> {
+ try {
+ if (ra.isReinitialize()) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Reliability resumption for action of reinitialize");
+ }
+ if (!isDestroyed() && !cache.isClosed()) {
+ RegionEventImpl event = new RegionEventImpl(this, Operation.REGION_REINITIALIZE, null,
+ false, getMyId(), generateEventID());
+ reinitialize(null, event);
+ }
+ synchronized (missingRequiredRoles) {
+ // any number of threads may be waiting on missingRequiredRoles
+ missingRequiredRoles.notifyAll();
+ if (hasListener() && id != null) {
+ // fire afterRoleGain event
+ RoleEventImpl relEvent = new RoleEventImpl(this, Operation.REGION_CREATE, null, true,
+ id, newlyAcquiredRoles);
+ dispatchListenerEvent(EnumListenerEvent.AFTER_ROLE_GAIN, relEvent);
}
}
- } catch (Exception e) {
- logger.fatal("Unexpected exception:", e);
}
+ } catch (Exception e) {
+ logger.fatal("Unexpected exception:", e);
}
});
}
@@ -816,23 +809,23 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
return; // early out: expiration was never affected by reliability
}
- if (getEntryTimeToLive().getTimeout() > 0
- && (isNoAccess || (isLimitedAccess && getEntryTimeToLive().getAction().isDistributed()))) {
+ if (getEntryTimeToLive().getTimeout() > 0 && (isNoAccess || getEntryTimeToLive().getAction()
+ .isDistributed())) {
rescheduleEntryExpiryTasks();
- } else if (getEntryIdleTimeout().getTimeout() > 0
- && (isNoAccess || (isLimitedAccess && getEntryIdleTimeout().getAction().isDistributed()))) {
+ } else if (getEntryIdleTimeout().getTimeout() > 0 && (isNoAccess || getEntryIdleTimeout()
+ .getAction().isDistributed())) {
rescheduleEntryExpiryTasks();
} else if (getCustomEntryTimeToLive() != null || getCustomEntryIdleTimeout() != null) {
// Force all entries to be rescheduled
rescheduleEntryExpiryTasks();
}
- if (getRegionTimeToLive().getTimeout() > 0
- && (isNoAccess || (isLimitedAccess && getRegionTimeToLive().getAction().isDistributed()))) {
+ if (getRegionTimeToLive().getTimeout() > 0 && (isNoAccess || getRegionTimeToLive().getAction()
+ .isDistributed())) {
addTTLExpiryTask();
}
- if (getRegionIdleTimeout().getTimeout() > 0 && (isNoAccess
- || (isLimitedAccess && getRegionIdleTimeout().getAction().isDistributed()))) {
+ if (getRegionIdleTimeout().getTimeout() > 0 && (isNoAccess || getRegionIdleTimeout().getAction()
+ .isDistributed())) {
addIdleExpiryTask();
}
}
@@ -887,7 +880,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
missingRequiredRoles.notifyAll();
// need to fire an event if id is not null
if (hasListener() && id != null) {
- RoleEventImpl relEvent = new RoleEventImpl(DistributedRegion.this,
+ RoleEventImpl relEvent = new RoleEventImpl(this,
Operation.CACHE_RECONNECT, null, true, id, newlyMissingRoles);
dispatchListenerEvent(EnumListenerEvent.AFTER_ROLE_LOSS, relEvent);
}
@@ -901,12 +894,12 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
} else {
getSystem().tryReconnect(false, "Role Loss", getCache()); // added for
// reconnect.
- synchronized (this.missingRequiredRoles) {
+ synchronized (missingRequiredRoles) {
// any number of threads may be waiting on missingRequiredRoles
- this.missingRequiredRoles.notifyAll();
+ missingRequiredRoles.notifyAll();
// need to fire an event if id is not null
if (hasListener() && id != null) {
- RoleEventImpl relEvent = new RoleEventImpl(DistributedRegion.this,
+ RoleEventImpl relEvent = new RoleEventImpl(this,
Operation.CACHE_RECONNECT, null, true, id, newlyMissingRoles);
dispatchListenerEvent(EnumListenerEvent.AFTER_ROLE_LOSS, relEvent);
}
@@ -920,16 +913,16 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
}
- void lockCheckReadiness() { // package-private to avoid synthetic accessor
+ private void lockCheckReadiness() { // package-private to avoid synthetic accessor
// fix for bug 32610
- this.cache.getCancelCriterion().checkCancelInProgress(null);
+ cache.getCancelCriterion().checkCancelInProgress(null);
checkReadiness();
}
@Override
Object validatedDestroy(Object key, EntryEventImpl event)
throws TimeoutException, EntryNotFoundException, CacheWriterException {
- Lock dlock = this.getDistributedLockIfGlobal(key);
+ Lock dlock = getDistributedLockIfGlobal(key);
try {
return super.validatedDestroy(key, event);
} finally {
@@ -944,7 +937,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
super.localDestroyNoCallbacks(key);
if (getScope().isGlobal()) {
try {
- this.getLockService().freeResources(key);
+ getLockService().freeResources(key);
} catch (LockServiceDestroyedException ignore) {
}
}
@@ -955,7 +948,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
super.localDestroy(key, aCallbackArgument);
if (getScope().isGlobal()) {
try {
- this.getLockService().freeResources(key);
+ getLockService().freeResources(key);
} catch (LockServiceDestroyedException ignore) {
}
}
@@ -967,7 +960,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
validateKey(key);
checkReadiness();
checkForLimitedOrNoAccess();
- Lock dlock = this.getDistributedLockIfGlobal(key);
+ Lock dlock = getDistributedLockIfGlobal(key);
try {
validatedInvalidate(key, aCallbackArgument);
} finally {
@@ -980,11 +973,11 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
public Lock getRegionDistributedLock() throws IllegalStateException {
lockCheckReadiness();
checkForLimitedOrNoAccess();
- if (!this.scope.isGlobal()) {
+ if (!scope.isGlobal()) {
throw new IllegalStateException(
String.format(
"Distribution locks are only supported for regions with GLOBAL scope, not %s",
- this.scope));
+ scope));
}
return new RegionDistributedLock();
}
@@ -994,11 +987,11 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
validateKey(key);
lockCheckReadiness();
checkForLimitedOrNoAccess();
- if (!this.scope.isGlobal()) {
+ if (!scope.isGlobal()) {
throw new IllegalStateException(
String.format(
"Distribution locks are only supported for regions with GLOBAL scope, not %s",
- this.scope));
+ scope));
}
if (isLockingSuspendedByCurrentThread()) {
throw new IllegalStateException(
@@ -1012,7 +1005,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
Set<String> allGatewaySenderIds = getAllGatewaySenderIds();
if (!allGatewaySenderIds.isEmpty()) {
- for (GatewaySender sender : this.cache.getAllGatewaySenders()) {
+ for (GatewaySender sender : cache.getAllGatewaySenders()) {
if (sender.isParallel() && allGatewaySenderIds.contains(sender.getId())) {
// Once decided to support REPLICATED regions with parallel
// gateway-sender/asynchronous-event-queue, ShadowPartitionedRegionForUserRR should be
@@ -1023,12 +1016,12 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
"Parallel Async Event Queue %s can not be used with replicated region %s",
AsyncEventQueueImpl.getAsyncEventQueueIdFromSenderId(sender.getId()),
- this.getFullPath()));
+ getFullPath()));
} else {
throw new GatewaySenderConfigurationException(
String.format(
"Parallel gateway sender %s can not be used with replicated region %s",
- sender.getId(), this.getFullPath()));
+ sender.getId(), getFullPath()));
}
}
}
@@ -1049,7 +1042,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
logger.debug("DistributedRegion.initialize BEGIN: {}", getFullPath());
}
- if (this.scope.isGlobal()) {
+ if (scope.isGlobal()) {
getLockService(); // create lock service eagerly now
}
@@ -1083,12 +1076,12 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
}
} catch (DiskAccessException dae) {
- this.handleDiskAccessException(dae, true);
+ handleDiskAccessException(dae, true);
throw dae;
}
initMembershipRoles();
- this.isInitializingThread = false;
+ isInitializingThread = false;
// makes sure all latches are released if they haven't been already
super.initialize(null, null, null);
} finally {
@@ -1114,7 +1107,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
InternalDistributedMember imageSrc, InternalRegionArguments internalRegionArgs,
boolean recoverFromDisk, PersistentMemberID persistentId) throws TimeoutException {
logger.info("Initializing region {}",
- this.getName());
+ getName());
ImageState imgState = getImageState();
imgState.init();
@@ -1124,11 +1117,11 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
throw new InternalGemFireError(
String.format(
"if loading a snapshot, then should not be recovering; isRecovering= %s ,snapshotStream= %s",
- new Object[] {true, snapshotInputStream}));
+ true, snapshotInputStream));
}
ProfileExchangeProcessor targetProvider;
- if (this.getDataPolicy().withPersistence()) {
+ if (getDataPolicy().withPersistence()) {
targetProvider =
new CreatePersistentRegionProcessor(this, getPersistenceAdvisor(), recoverFromDisk);
} else {
@@ -1137,23 +1130,23 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
imgState.setInRecovery(false);
RegionVersionVector recovered_rvv = null;
- if (this.getDataPolicy().withPersistence()) {
- recovered_rvv = this.getVersionVector() == null ? null
- : this.getVersionVector().getCloneForTransmission();
+ if (getDataPolicy().withPersistence()) {
+ recovered_rvv = getVersionVector() == null ? null
+ : getVersionVector().getCloneForTransmission();
}
// initializeRegion will send out our profile
targetProvider.initializeRegion();
- if (this.persistenceAdvisor != null) {
- this.persistenceAdvisor.initialize();
+ if (persistenceAdvisor != null) {
+ persistenceAdvisor.initialize();
}
// Register listener here so that the remote members are known
// since registering calls initializeCriticalMembers (which needs to know about
// remote members
if (!isInternalRegion()) {
- if (!this.isDestroyed) {
- this.cache.getInternalResourceManager().addResourceListener(ResourceType.MEMORY, this);
+ if (!isDestroyed) {
+ cache.getInternalResourceManager().addResourceListener(ResourceType.MEMORY, this);
}
}
@@ -1171,10 +1164,8 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
isInitialized(), getFullPath());
}
loadSnapshotDuringInitialization(snapshotInputStream);
- } catch (IOException e) {
- throw new RuntimeException(e); // TODO: change this exception?
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e); // TODO: change this exception?
+ } catch (IOException | ClassNotFoundException e) {
+ throw new RuntimeException(e);
}
cleanUpDestroyedTokensAndMarkGIIComplete(GIIStatus.NO_GII);
return;
@@ -1186,15 +1177,14 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
// treat it like it is a replicate (regardless of whether it actually is
// or not)
- InitialImageOperation iiop = new InitialImageOperation(this, this.entries);
+ InitialImageOperation iiop = new InitialImageOperation(this, entries);
CacheDistributionAdvisor.InitialImageAdvice advice = null;
- boolean done = false;
- while (!done && !isDestroyed()) {
+ while (!isDestroyed()) {
advice = targetProvider.getInitialImageAdvice(advice);
boolean attemptGetFromOne = imageSrc != null // we were given a specific member
- || this.getDataPolicy().withPreloaded() && !advice.preloaded.isEmpty() // this is a
- // preloaded
+ || getDataPolicy().withPreloaded() && !advice.preloaded.isEmpty() // this is a
+ // preloaded
// region
|| (!advice.replicates.isEmpty());
// That is: if we have 0 or 1 giiProvider then we can do a getFromOne gii;
@@ -1219,9 +1209,8 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
GIIStatus ret = iiop.getFromOne(Collections.singleton(imageSrc), targetRecreated,
advice, recoverFromDisk, recovered_rvv);
if (GIIStatus.didGII(ret)) {
- this.giiMissingRequiredRoles = false;
+ giiMissingRequiredRoles = false;
cleanUpDestroyedTokensAndMarkGIIComplete(ret);
- done = true;
return;
}
} finally {
@@ -1234,17 +1223,15 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
iiop.getFromOne(advice.replicates, false, advice, recoverFromDisk, recovered_rvv);
if (GIIStatus.didGII(ret)) {
cleanUpDestroyedTokensAndMarkGIIComplete(ret);
- done = true;
return;
}
// Plan D: if this is a PRELOADED region, fetch from another PRELOADED
- if (this.getDataPolicy().isPreloaded()) {
+ if (getDataPolicy().isPreloaded()) {
GIIStatus ret_preload =
iiop.getFromOne(advice.preloaded, false, advice, recoverFromDisk, recovered_rvv);
if (GIIStatus.didGII(ret_preload)) {
cleanUpDestroyedTokensAndMarkGIIComplete(ret_preload);
- done = true;
return;
}
} // isPreloaded
@@ -1260,25 +1247,24 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
if (recoverFromDisk) {
logger.info(
"Region {} recovered from the local disk. Old persistent ID: {}, new persistent ID {}",
- new Object[] {this.getFullPath(), persistentId, getPersistentID()});
+ new Object[] {getFullPath(), persistentId, getPersistentID()});
if (persistentId != null) {
- RegionLogger.logRecovery(this.getFullPath(), persistentId,
+ RegionLogger.logRecovery(getFullPath(), persistentId,
getDistributionManager().getDistributionManagerId());
}
} else {
- RegionLogger.logCreate(this.getFullPath(),
+ RegionLogger.logCreate(getFullPath(),
getDistributionManager().getDistributionManagerId());
if (getPersistentID() != null) {
- RegionLogger.logPersistence(this.getFullPath(),
+ RegionLogger.logPersistence(getFullPath(),
getDistributionManager().getDistributionManagerId(), getPersistentID());
logger.info("Region {} was created on this member with the persistent id {}.",
- new Object[] {this.getFullPath(), getPersistentID()});
+ new Object[] {getFullPath(), getPersistentID()});
}
}
cleanUpDestroyedTokensAndMarkGIIComplete(GIIStatus.NO_GII);
- done = true;
return;
}
break;
@@ -1292,7 +1278,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
*/
public void synchronizeForLostMember(InternalDistributedMember lostMember,
VersionSource lostVersionID) {
- if (!this.getConcurrencyChecksEnabled()) {
+ if (!getConcurrencyChecksEnabled()) {
return;
}
CacheDistributionAdvisor advisor = getCacheDistributionAdvisor();
@@ -1308,7 +1294,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
*/
private void synchronizeWith(InternalDistributedMember target, VersionSource versionMember,
InternalDistributedMember lostMember) {
- InitialImageOperation op = new InitialImageOperation(this, this.entries);
+ InitialImageOperation op = new InitialImageOperation(this, entries);
op.synchronizeWith(target, versionMember, lostMember);
}
@@ -1335,9 +1321,9 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
getImageState().getLeftMembers();
getImageState().getVersionTags();
// Clear OQL indexes
- if (this.indexManager != null) {
+ if (indexManager != null) {
try {
- this.indexManager.rerunIndexCreationQuery();
+ indexManager.rerunIndexCreationQuery();
} catch (Exception ex) {
if (logger.isDebugEnabled()) {
logger.debug("Exception while clearing indexes after GII failure.", ex);
@@ -1362,7 +1348,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
failedInitialImageLock.readLock().lock();
}
- void unlockFailedInitialImageReadLock() {
+ private void unlockFailedInitialImageReadLock() {
failedInitialImageLock.readLock().unlock();
}
@@ -1381,21 +1367,22 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
private void initMembershipRoles() {
- synchronized (this.advisorListener) {
+ synchronized (advisorListener) {
// hold sync to prevent listener from changing initial members
- Set others = this.distAdvisor.addMembershipListenerAndAdviseGeneric(this.advisorListener);
- this.advisorListener.addMembers(others);
+ Set<InternalDistributedMember> others =
+ distAdvisor.addMembershipListenerAndAdviseGeneric(advisorListener);
+ advisorListener.addMembers(others);
// initialize missing required roles with initial member info
if (getMembershipAttributes().hasRequiredRoles()) {
// AdvisorListener will also sync on missingRequiredRoles
- synchronized (this.missingRequiredRoles) {
- this.missingRequiredRoles.addAll(getMembershipAttributes().getRequiredRoles());
+ synchronized (missingRequiredRoles) {
+ missingRequiredRoles.addAll(getMembershipAttributes().getRequiredRoles());
// remove all the roles we are playing since they will never be
// missing
- this.missingRequiredRoles.removeAll(getSystem().getDistributedMember().getRoles());
+ missingRequiredRoles.removeAll(getSystem().getDistributedMember().getRoles());
for (Object other1 : others) {
DistributedMember other = (DistributedMember) other1;
- this.missingRequiredRoles.removeAll(other.getRoles());
+ missingRequiredRoles.removeAll(other.getRoles());
}
}
}
@@ -1408,13 +1395,13 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
logger.debug("Waiting up to {} for required roles.", memberTimeout);
}
try {
- if (this.giiMissingRequiredRoles) {
+ if (giiMissingRequiredRoles) {
// force reliability loss and possibly resumption
- this.isInitializingThread = true;
- synchronized (this.advisorListener) {
- synchronized (this.missingRequiredRoles) {
+ isInitializingThread = true;
+ synchronized (advisorListener) {
+ synchronized (missingRequiredRoles) {
// forcing state of loss because of bad GII
- this.isMissingRequiredRoles = true;
+ isMissingRequiredRoles = true;
getCachePerfStats().incReliableRegionsMissing(1);
if (getMembershipAttributes().getLossAction().isAllAccess())
getCachePerfStats().incReliableRegionsMissingFullAccess(1); // rahul
@@ -1427,11 +1414,11 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
logger.debug("GetInitialImage had missing required roles.");
}
// TODO: will this work with RECONNECT and REINITIALIZE?
- this.isInitializingThread = true;
+ isInitializingThread = true;
lostReliability(null, null);
- if (this.missingRequiredRoles.isEmpty()) {
+ if (missingRequiredRoles.isEmpty()) {
// all required roles are present so force resumption
- this.isMissingRequiredRoles = false;
+ isMissingRequiredRoles = false;
getCachePerfStats().incReliableRegionsMissing(-1);
if (getMembershipAttributes().getLossAction().isAllAccess())
getCachePerfStats().incReliableRegionsMissingFullAccess(-1); // rahul
@@ -1442,7 +1429,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
// pur code to increment the stats.
boolean async = resumeReliability(null, null);
if (async) {
- this.advisorListener.destroyed = true;
+ advisorListener.destroyed = true;
}
}
}
@@ -1452,16 +1439,16 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
waitForRequiredRoles(memberTimeout);
}
boolean initiateLossAction = false;
- synchronized (this.advisorListener) {
- synchronized (this.missingRequiredRoles) {
- if (this.missingRequiredRoles.isEmpty()) {
- Assert.assertTrue(!this.isMissingRequiredRoles);
+ synchronized (advisorListener) {
+ synchronized (missingRequiredRoles) {
+ if (missingRequiredRoles.isEmpty()) {
+ Assert.assertTrue(!isMissingRequiredRoles);
if (logger.isDebugEnabled()) {
logger.debug("Initialization completed with all required roles present.");
}
} else {
// starting in state of loss...
- this.isMissingRequiredRoles = true;
+ isMissingRequiredRoles = true;
getCachePerfStats().incReliableRegionsMissing(1);
if (getMembershipAttributes().getLossAction().isAllAccess())
getCachePerfStats().incReliableRegionsMissingFullAccess(1); // rahul
@@ -1472,9 +1459,9 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
if (logger.isDebugEnabled()) {
logger.debug("Initialization completed with missing required roles: {}",
- this.missingRequiredRoles);
+ missingRequiredRoles);
}
- this.isInitializingThread = true;
+ isInitializingThread = true;
initiateLossAction = true;
}
}
@@ -1487,7 +1474,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
// ignore to fix bug 34639 may be thrown by waitForRequiredRoles
} catch (CancelException e) {
// ignore to fix bug 34639 may be thrown by waitForRequiredRoles
- if (this.isInitializingThread) {
+ if (isInitializingThread) {
throw e;
}
} catch (Exception e) {
@@ -1496,7 +1483,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
// open latch which will allow any threads in lostReliability to proceed
- this.initializationLatchAfterMemberTimeout.countDown();
+ initializationLatchAfterMemberTimeout.countDown();
}
private boolean isRecoveryNeeded() {
@@ -1521,9 +1508,9 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
// remove DESTROYED tokens
RegionVersionVector rvv = is.getClearRegionVersionVector();
try {
- Iterator/* <Object> */ keysIt = getImageState().getDestroyedEntries();
+ Iterator<Object> keysIt = getImageState().getDestroyedEntries();
while (keysIt.hasNext()) {
- this.entries.removeIfDestroyed(keysIt.next());
+ entries.removeIfDestroyed(keysIt.next());
}
if (rvv != null) {
// clear any entries received in the GII that are older than the RVV versions.
@@ -1532,8 +1519,8 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
clearEntries(rvv);
}
// need to do this before we release the afterGetInitialImageLatch
- if (this.persistenceAdvisor != null) {
- this.persistenceAdvisor.setOnline(GIIStatus.didGII(giiStatus), false, getPersistentID());
+ if (persistenceAdvisor != null) {
+ persistenceAdvisor.setOnline(GIIStatus.didGII(giiStatus), false, getPersistentID());
}
} finally {
// release after gii lock first so basicDestroy will see isInitialized()
@@ -1552,7 +1539,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
// "Initializing region {0}" which is not acompanied by a completed message. Users think thread
// is stuck in some operation. Hence adding this log
- logger.info("Initialization of region {} completed", this.getName());
+ logger.info("Initialization of region {} completed", getName());
}
@Override
@@ -1615,23 +1602,23 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
try {
boolean invokeWriter = cacheWrite;
- if (this.requiresOneHopForMissingEntry(event)) {
+ if (requiresOneHopForMissingEntry(event)) {
// bug #45704: see if a one-hop must be done for this operation
RegionEntry re = getRegionEntry(event.getKey());
- if (re == null /* || re.isTombstone() */ || !this.generateVersionTag) {
+ if (re == null /* || re.isTombstone() */ || !generateVersionTag) {
if (getServerProxy() == null) {
// only assert for non-client regions.
- Assert.assertTrue(!this.getDataPolicy().withReplication() || !this.generateVersionTag);
+ Assert.assertTrue(!getDataPolicy().withReplication() || !generateVersionTag);
}
- if (!event.isBulkOpInProgress() || this.getDataPolicy().withStorage()) {
+ if (!event.isBulkOpInProgress() || getDataPolicy().withStorage()) {
// removeAll will send a single one-hop for empty regions. for other missing entries
// we need to get a valid version number before modifying the local cache
// TODO: deltaGII: verify that delegating to a peer when this region is also a client is
// acceptable
boolean didDistribute =
- RemoteDestroyMessage.distribute(event, expectedOldValue, !this.generateVersionTag);
+ RemoteDestroyMessage.distribute(event, expectedOldValue, !generateVersionTag);
- if (!this.generateVersionTag && !didDistribute) {
+ if (!generateVersionTag && !didDistribute) {
throw new PersistentReplicatesOfflineException();
}
@@ -1656,7 +1643,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
// if this is a destroy coming in from remote source, free up lock resources
// if this is a local origin destroy, this will happen after lock is
// released
- if (this.scope.isGlobal() && event.isOriginRemote()) {
+ if (scope.isGlobal() && event.isOriginRemote()) {
try {
getLockService().freeResources(event.getKey());
} catch (LockServiceDestroyedException ignore) {
@@ -1700,7 +1687,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
boolean evictDestroy(EvictableEntry entry) {
boolean evictDestroyWasDone = super.evictDestroy(entry);
if (evictDestroyWasDone) {
- if (this.scope.isGlobal()) {
+ if (scope.isGlobal()) {
try {
getLockService().freeResources(entry.getKey());
} catch (LockServiceDestroyedException ignore) {
@@ -1752,7 +1739,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
// when another member concurrently creates this region. See bug 42051.
boolean isClose = event.getOperation().isClose();
if (!isClose) {
- this.cache.beginDestroy(path, this);
+ cache.beginDestroy(path, this);
}
try {
super.basicDestroyRegion(event, cacheWrite, lock, callbackEvents);
@@ -1775,7 +1762,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
} finally {
if (!isClose) {
- this.cache.endDestroy(path, this);
+ cache.endDestroy(path, this);
}
RegionLogger.logDestroy(path, getMyId(), getPersistentID(), isClose);
}
@@ -1783,8 +1770,8 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
void distributeDestroyRegion(RegionEventImpl event, boolean notifyOfRegionDeparture) {
- if (this.persistenceAdvisor != null) {
- this.persistenceAdvisor.releaseTieLock();
+ if (persistenceAdvisor != null) {
+ persistenceAdvisor.releaseTieLock();
}
new DestroyRegionOperation(event, notifyOfRegionDeparture).distribute();
}
@@ -1807,19 +1794,19 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
throw new IllegalStateException(
"Not allowed to do a local invalidation on a replicated region");
}
- if (this.requiresOneHopForMissingEntry(event)) {
+ if (requiresOneHopForMissingEntry(event)) {
// bug #45704: see if a one-hop must be done for this operation
RegionEntry re = getRegionEntry(event.getKey());
- if (re == null/* || re.isTombstone() */ || !this.generateVersionTag) {
+ if (re == null/* || re.isTombstone() */ || !generateVersionTag) {
if (getServerProxy() == null) {
// only assert for non-client regions.
- Assert.assertTrue(!this.getDataPolicy().withReplication() || !this.generateVersionTag);
+ Assert.assertTrue(!getDataPolicy().withReplication() || !generateVersionTag);
}
// TODO: deltaGII: verify that delegating to a peer when this region is also a client is
// acceptable
boolean didDistribute =
- RemoteInvalidateMessage.distribute(event, !this.generateVersionTag);
- if (!this.generateVersionTag && !didDistribute) {
+ RemoteInvalidateMessage.distribute(event, !generateVersionTag);
+ if (!generateVersionTag && !didDistribute) {
throw new PersistentReplicatesOfflineException();
}
if (didDistribute) {
@@ -1854,7 +1841,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
void distributeInvalidate(EntryEventImpl event) {
- if (!this.isRegionInvalid() && event.isDistributed() && !event.isOriginRemote()
+ if (!isRegionInvalid() && event.isDistributed() && !event.isOriginRemote()
&& !isTX() /* only distribute if non-tx */) {
if (event.isDistributed() && !event.isOriginRemote()) {
boolean distribute = !event.getInhibitDistribution();
@@ -1892,7 +1879,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
void distributeUpdateEntryVersion(EntryEventImpl event) {
- if (!this.isRegionInvalid() && event.isDistributed() && !event.isOriginRemote()
+ if (!isRegionInvalid() && event.isDistributed() && !event.isOriginRemote()
&& !isTX() /* only distribute if non-tx */) {
if (event.isDistributed() && !event.isOriginRemote()) {
// before distribute: DR has sent callback earlier
@@ -1904,7 +1891,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
protected void basicClear(RegionEventImpl regionEvent) {
- Lock dlock = this.getRegionDistributedLockIfGlobal();
+ Lock dlock = getRegionDistributedLockIfGlobal();
try {
super.basicClear(regionEvent);
} finally {
@@ -1915,11 +1902,11 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
void basicClear(RegionEventImpl regionEvent, boolean cacheWrite) {
- if (this.getConcurrencyChecksEnabled() && !this.getDataPolicy().withReplication()) {
+ if (getConcurrencyChecksEnabled() && !getDataPolicy().withReplication()) {
boolean retry = false;
do {
// non-replicate regions must defer to a replicate for clear/invalidate of region
- Set<InternalDistributedMember> repls = this.distAdvisor.adviseReplicates();
+ Set<InternalDistributedMember> repls = distAdvisor.adviseReplicates();
if (!repls.isEmpty()) {
InternalDistributedMember mbr = repls.iterator().next();
RemoteClearMessage op = RemoteClearMessage.create(mbr, this);
@@ -1940,14 +1927,14 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
void cmnClearRegion(RegionEventImpl regionEvent, boolean cacheWrite, boolean useRVV) {
- boolean enableRVV = useRVV && this.getDataPolicy().withReplication()
- && this.getConcurrencyChecksEnabled() && !getDistributionManager().isLoner();
+ boolean enableRVV = useRVV && getDataPolicy().withReplication()
+ && getConcurrencyChecksEnabled() && !getDistributionManager().isLoner();
// Fix for 46338 - apparently multiple threads from the same VM are allowed
// to suspend locking, which is what distributedLockForClear() does. We don't
// want that to happen, so we'll synchronize to make sure only one thread on
// this member performs a clear.
- synchronized (this.clearLock) {
+ synchronized (clearLock) {
if (enableRVV) {
distributedLockForClear();
@@ -1987,7 +1974,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
* Obtain a distributed lock for the clear operation.
*/
private void distributedLockForClear() {
- if (!this.scope.isGlobal()) { // non-global regions must lock when using RVV
+ if (!scope.isGlobal()) { // non-global regions must lock when using RVV
try {
getLockService().lock("_clearOperation", -1, -1);
} catch (IllegalStateException e) {
@@ -2001,7 +1988,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
* Release the distributed lock for the clear operation.
*/
private void distributedUnlockForClear() {
- if (!this.scope.isGlobal()) {
+ if (!scope.isGlobal()) {
try {
getLockService().unlock("_clearOperation");
} catch (IllegalStateException e) {
@@ -2041,7 +2028,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
// we don't continue a clear if the region has been destroyed.
checkReadiness();
// Only need to flush if NOACK at this point
- if (this.getAttributes().getScope().isDistributedNoAck()) {
+ if (getAttributes().getScope().isDistributedNoAck()) {
Set<InternalDistributedMember> members = getDistributionAdvisor().adviseCacheOp();
StateFlushOperation.flushTo(members, this);
}
@@ -2077,7 +2064,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
private void waitForInProgressClear() {
RegionVersionVector rvv = getVersionVector();
if (rvv != null) {
- synchronized (this.clearLock) {
+ synchronized (clearLock) {
// do nothing;
// I'm a little scared that the compiler might optimize
// away this synchronization if we really do nothing. Hence
@@ -2094,7 +2081,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
* Distribute Tombstone garbage-collection information to all peers with storage
*/
protected EventID distributeTombstoneGC(Set<Object> keysRemoved) {
- this.getCachePerfStats().incTombstoneGCCount();
+ getCachePerfStats().incTombstoneGCCount();
EventID eventId = new EventID(getSystem());
DistributedTombstoneOperation gc = DistributedTombstoneOperation.gc(this, eventId);
gc.distribute();
@@ -2118,26 +2105,26 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
public CacheDistributionAdvisor getDistributionAdvisor() {
- return this.distAdvisor;
+ return distAdvisor;
}
@Override
public CacheDistributionAdvisor getCacheDistributionAdvisor() {
- return this.distAdvisor;
+ return distAdvisor;
}
public PersistenceAdvisor getPersistenceAdvisor() {
- return this.persistenceAdvisor;
+ return persistenceAdvisor;
}
public PersistentMemberID getPersistentID() {
- return this.persistentId;
+ return persistentId;
}
/** Returns the distribution profile; lazily creates one if needed */
@Override
public Profile getProfile() {
- return this.distAdvisor.createProfile();
+ return distAdvisor.createProfile();
}
@Override
@@ -2148,8 +2135,8 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
cacheProfile.hasCacheLoader = basicGetLoader() != null;
cacheProfile.hasCacheWriter = basicGetWriter() != null;
cacheProfile.hasCacheListener = hasListener();
- Assert.assertTrue(this.scope.isDistributed());
- cacheProfile.scope = this.scope;
+ Assert.assertTrue(scope.isDistributed());
+ cacheProfile.scope = scope;
cacheProfile.inRecovery = getImageState().getInRecovery();
cacheProfile.isPersistent = getDataPolicy().withPersistence();
cacheProfile.setSubscriptionAttributes(getSubscriptionAttributes());
@@ -2167,9 +2154,9 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
if (getPersistenceAdvisor() != null) {
cacheProfile.persistenceInitialized = getPersistenceAdvisor().isOnline();
}
- cacheProfile.hasCacheServer = this.cache.getCacheServers().size() > 0 ? true : false;
- cacheProfile.requiresOldValueInEvents = this.getDataPolicy().withReplication()
- && this.filterProfile != null && this.filterProfile.hasCQs();
+ cacheProfile.hasCacheServer = !cache.getCacheServers().isEmpty();
+ cacheProfile.requiresOldValueInEvents = getDataPolicy().withReplication()
+ && filterProfile != null && filterProfile.hasCQs();
cacheProfile.gatewaySenderIds = getGatewaySenderIds();
cacheProfile.asyncEventQueueIds = getVisibleAsyncEventQueueIds();
cacheProfile.isOffHeap = getOffHeap();
@@ -2180,47 +2167,47 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
* that service the first time it is invoked on this region.
*/
public DistributedLockService getLockService() {
- synchronized (this.dlockMonitor) {
+ synchronized (dlockMonitor) {
String dlsName = getFullPath();
- if (this.dlockService == null) {
- this.dlockService = DistributedLockService.getServiceNamed(dlsName);
- if (this.dlockService == null) {
+ if (dlockService == null) {
+ dlockService = DistributedLockService.getServiceNamed(dlsName);
+ if (dlockService == null) {
// region destroy will destroy dls and manual freeResources only
- this.dlockService = DLockService.create(getFullPath(), getSystem(), true, false, false);
+ dlockService = DLockService.create(getFullPath(), getSystem(), true, false, false);
}
// handle is-lock-grantor region attribute...
- if (this.isLockGrantor) {
- this.dlockService.becomeLockGrantor();
+ if (isLockGrantor) {
+ dlockService.becomeLockGrantor();
}
if (logger.isDebugEnabled()) {
logger.debug("LockService for {} is using LockLease={}, LockTimeout={}", dlsName,
getCache().getLockLease(), getCache().getLockTimeout());
}
}
- return this.dlockService;
+ return dlockService;
}
}
@Override
boolean isCurrentlyLockGrantor() {
- return this.scope.isGlobal() && getLockService().isLockGrantor();
+ return scope.isGlobal() && getLockService().isLockGrantor();
}
@Override
public boolean isLockGrantor() {
- return this.scope.isGlobal() && this.isLockGrantor;
+ return scope.isGlobal() && isLockGrantor;
}
@Override
public void becomeLockGrantor() {
checkReadiness();
checkForLimitedOrNoAccess();
- if (!this.scope.isGlobal()) {
+ if (!scope.isGlobal()) {
throw new IllegalStateException(
String.format(
"Distribution locks are only supported for regions with GLOBAL scope, not %s",
- this.scope));
+ scope));
}
DistributedLockService svc = getLockService();
@@ -2327,11 +2314,12 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
private void updateEventWithCurrentRegionEntry(EntryEventImpl event, EntryEventImpl clientEvent) {
// defer the lruUpdateCallback to prevent a deadlock (see bug 51121).
- final boolean disabled = this.entries.disableLruUpdateCallback();
+ final boolean disabled = entries.disableLruUpdateCallback();
try {
RegionEntry re = getRegionEntry(event.getKey());
if (re != null) {
- synchronized (re) { // bug #51059 value & version must be obtained atomically
+ synchronized (re) {
+ // value & version must be obtained atomically
// Update client event with latest version tag from re
if (clientEvent != null) {
clientEvent.setVersionTag(re.getVersionStamp().asVersionTag());
@@ -2342,12 +2330,12 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
} finally {
if (disabled) {
- this.entries.enableLruUpdateCallback();
+ entries.enableLruUpdateCallback();
}
try {
- this.entries.lruUpdateCallback();
+ entries.lruUpdateCallback();
} catch (DiskAccessException dae) {
- this.handleDiskAccessException(dae);
+ handleDiskAccessException(dae);
throw dae;
}
}
@@ -2415,7 +2403,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
boolean result = false;
if (event.isDistributed()) {
CacheWriter localWriter = basicGetWriter();
- Set netWriteRecipients = localWriter == null ? this.distAdvisor.adviseNetWrite() : null;
+ Set netWriteRecipients = localWriter == null ? distAdvisor.adviseNetWrite() : null;
if ((localWriter != null || (netWriteRecipients != null && !netWriteRecipients.isEmpty()))
&& !event.inhibitAllNotifications()) {
@@ -2446,7 +2434,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
boolean result = false;
if (event.getOperation().isDistributed()) {
CacheWriter localWriter = basicGetWriter();
- Set netWriteRecipients = localWriter == null ? this.distAdvisor.adviseNetWrite() : null;
+ Set netWriteRecipients = localWriter == null ? distAdvisor.adviseNetWrite() : null;
if (localWriter != null || netWriteRecipients != null && !netWriteRecipients.isEmpty()) {
final long start = getCachePerfStats().startCacheWriterCall();
@@ -2475,24 +2463,24 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
// (REGION_REINITIALIZE)
// or if event is null then this was a failed initialize (create)
// wake up any threads in waitForRequiredRoles... they will checkReadiness
- synchronized (this.missingRequiredRoles) {
- this.missingRequiredRoles.notifyAll();
+ synchronized (missingRequiredRoles) {
+ missingRequiredRoles.notifyAll();
}
}
- if (this.persistenceAdvisor != null) {
- this.persistenceAdvisor.close(); // fix for bug 41094
+ if (persistenceAdvisor != null) {
+ persistenceAdvisor.close(); // fix for bug 41094
}
- this.distAdvisor.close();
+ distAdvisor.close();
// Fix for bug 46338. Wait for in progress clears before destroying the
// lock service, because destroying the service immediately releases the dlock
waitForInProgressClear();
DLockService dls = null;
- synchronized (this.dlockMonitor) {
- if (this.dlockService != null) {
- dls = (DLockService) this.dlockService;
+ synchronized (dlockMonitor) {
+ if (dlockService != null) {
+ dls = (DLockService) dlockService;
}
}
if (dls != null) {
@@ -2505,28 +2493,27 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
} catch (Exception ex) {
logger.warn("DLS destroy may have failed for " +
- this.getFullPath(),
+ getFullPath(),
ex);
}
}
waitForCurrentOperations();
}
- protected void waitForCurrentOperations() {
+ private void waitForCurrentOperations() {
// Fix for #48066 - make sure that region operations are completely
// distributed to peers before destroying the region.
boolean flushOnClose =
!Boolean.getBoolean(DistributionConfig.GEMFIRE_PREFIX + "no-flush-on-close"); // test hook
- if (!this.cache.forcedDisconnect() && flushOnClose
- && this.getDistributionManager().getMembershipManager() != null
- && this.getDistributionManager().getMembershipManager().isConnected()) {
+ if (!cache.forcedDisconnect() && flushOnClose
+ && getDistributionManager().getMembershipManager() != null
+ && getDistributionManager().getMembershipManager().isConnected()) {
getDistributionAdvisor().forceNewMembershipVersion();
try {
getDistributionAdvisor().waitForCurrentOperations();
} catch (Exception e) {
// log this but try to close the region so that listeners are invoked
- logger.warn(String.format("%s: error closing region %s",
- new Object[] {this, getFullPath()}), e);
+ logger.warn(String.format("%s: error closing region %s", this, getFullPath()), e);
}
}
}
@@ -2538,16 +2525,15 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
public void postCreateRegion() {
super.postCreateRegion();
// should we sync on this.distAdvisor first to prevent bug 44369?
- synchronized (this.advisorListener) {
- Set others = this.advisorListener.getInitialMembers();
+ synchronized (advisorListener) {
+ Set<InternalDistributedMember> others = advisorListener.getInitialMembers();
CacheListener[] listeners = fetchCacheListenersField();
if (listeners != null) {
for (CacheListener listener : listeners) {
if (listener instanceof RegionMembershipListener) {
RegionMembershipListener regionMembershipListener = (RegionMembershipListener) listener;
try {
- DistributedMember[] otherDms = new DistributedMember[others.size()];
- others.toArray(otherDms);
+ DistributedMember[] otherDms = others.toArray(new DistributedMember[0]);
regionMembershipListener.initialMembers(this, otherDms);
} catch (VirtualMachineError err) {
SystemFailure.initiateFailure(err);
@@ -2652,7 +2638,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
protected void cacheListenersChanged(boolean nowHasListener) {
if (nowHasListener) {
- this.advisorListener.initRMLWrappers();
+ advisorListener.initRMLWrappers();
}
new UpdateAttributesProcessor(this).distribute();
}
@@ -2700,23 +2686,23 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
void checkSameSenderIdsAvailableOnAllNodes() {
List<Set<String>> senderIds =
- this.getCacheDistributionAdvisor().adviseSameGatewaySenderIds(getGatewaySenderIds());
+ getCacheDistributionAdvisor().adviseSameGatewaySenderIds(getGatewaySenderIds());
if (!senderIds.isEmpty()) {
throw new GatewaySenderConfigurationException(
String.format(
"Region %s has %s gateway sender IDs. Another cache has same region with %s gateway sender IDs. For region across all members, gateway sender ids should be same.",
- new Object[] {this.getName(), senderIds.get(0), senderIds.get(1)}));
+ getName(), senderIds.get(0), senderIds.get(1)));
}
- List<Set<String>> asycnQueueIds = this.getCacheDistributionAdvisor()
+ List<Set<String>> asycnQueueIds = getCacheDistributionAdvisor()
.adviseSameAsyncEventQueueIds(getVisibleAsyncEventQueueIds());
if (!asycnQueueIds.isEmpty()) {
throw new GatewaySenderConfigurationException(
String.format(
"Region %s has %s AsyncEvent queue IDs. Another cache has same region with %s AsyncEvent queue IDs. For region across all members, AsyncEvent queue IDs should be same.",
- new Object[] {this.getName(), asycnQueueIds.get(0), asycnQueueIds.get(1)}));
+ getName(), asycnQueueIds.get(0), asycnQueueIds.get(1)));
}
}
@@ -2751,7 +2737,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
String msg = null;
Object[] msgArgs = null;
while (timeLeft > 0 || lockTimeout == -1) {
- this.cache.getCancelCriterion().checkCancelInProgress(null);
+ cache.getCancelCriterion().checkCancelInProgress(null);
boolean interrupted = Thread.interrupted();
try {
Lock dlock = getDistributedLock(key);
@@ -2764,7 +2750,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
return dlock;
} catch (InterruptedException ex) {
interrupted = true;
- this.cache.getCancelCriterion().checkCancelInProgress(ex);
+ cache.getCancelCriterion().checkCancelInProgress(ex);
// TODO: Why is it OK to keep going?
if (lockTimeout > -1) {
timeLeft = getCache().getLockTimeout() - (System.currentTimeMillis() - start) / 1000L;
@@ -2801,7 +2787,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
*/
@Override
public Iterator<RegionEntry> getBestIterator(boolean includeValues) {
- DiskRegion dr = this.getDiskRegion();
+ DiskRegion dr = getDiskRegion();
if (DiskPage.DISK_PAGE_SIZE > 0 && includeValues && dr != null) {
// Wait for the disk region to recover values first.
@@ -2810,7 +2796,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
return new DiskSavvyIterator();
}
}
- return this.entries.regionEntries().iterator();
+ return entries.regionEntries().iterator();
}
/**
@@ -2835,20 +2821,20 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
public boolean hasNext() {
boolean result;
- if (this.subIt != null) {
- result = this.subIt.hasNext();
+ if (subIt != null) {
+ result = subIt.hasNext();
if (!result) {
- this.subIt = null;
+ subIt = null;
} else {
return result;
}
}
- result = this.it.hasNext();
- if (this.usingIt && !result) {
- this.usingIt = false;
- this.it = this.diskMap.values().iterator();
- result = this.it.hasNext();
+ result = it.hasNext();
+ if (usingIt && !result) {
+ usingIt = false;
+ it = diskMap.values().iterator();
+ result = it.hasNext();
}
return result;
}
@@ -2856,39 +2842,37 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
public RegionEntry next() {
for (;;) {
- if (this.subIt != null) {
- return this.subIt.next();
+ if (subIt != null) {
+ return subIt.next();
}
- if (this.usingIt) {
- RegionEntry regionEntry = (RegionEntry) this.it.next();
+ if (usingIt) {
+ RegionEntry regionEntry = (RegionEntry) it.next();
DiskPosition diskPosition = new DiskPosition();
if (regionEntry.isOverflowedToDisk(DistributedRegion.this, diskPosition)) {
// add diskPosition to sorted list
DiskPage dPage = new DiskPage(diskPosition);
- Object value = this.diskMap.get(dPage);
+ Object value = diskMap.get(dPage);
if (value == null) {
- this.diskMap.put(dPage, regionEntry);
+ diskMap.put(dPage, regionEntry);
} else if (value instanceof ArrayList) {
- List list = (List) value;
+ List<Object> list = (ArrayList<Object>) value;
list.add(regionEntry);
} else {
- List list = new ArrayList();
+ List<Object> list = new ArrayList<>();
list.add(value);
list.add(regionEntry);
- this.diskMap.put(dPage, list);
- }
- if (!hasNext()) {
- assert false; // must be true
+ diskMap.put(dPage, list);
}
+ assert hasNext(); // must be true
} else {
return regionEntry;
}
} else {
- Object value = this.it.next();
+ Object value = it.next();
if (value instanceof ArrayList) {
- List list = (List) value;
- this.subIt = list.iterator();
- return this.subIt.next();
+ List<RegionEntry> list = (List<RegionEntry>) value;
+ subIt = list.iterator();
+ return subIt.next();
} else {
return (RegionEntry) value;
}
@@ -2916,14 +2900,14 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
public int hashCode() {
// TODO: Object instantiation inside 'hashCode()' is bad
- return Long.valueOf(this.oplogId ^ this.offset).hashCode();
+ return Long.valueOf(oplogId ^ offset).hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof DiskPosition) {
DiskPosition other = (DiskPosition) obj;
- return this.oplogId == other.oplogId && this.offset == other.offset;
+ return oplogId == other.oplogId && offset == other.offset;
} else {
return false;
}
@@ -2931,18 +2915,16 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
public int compareTo(DiskPosition o) {
- int result = Long.signum(this.oplogId - o.oplogId);
+ int result = Long.signum(oplogId - o.oplogId);
if (result == 0) {
- result = Long.signum(this.offset - o.offset);
+ result = Long.signum(offset - o.offset);
}
return result;
}
@Override
public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append('<').append(this.oplogId).append(':').append(this.offset).append('>');
- return sb.toString();
+ return "<" + oplogId + ':' + offset + '>';
}
}
@@ -2952,7 +2934,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
Long.getLong(DistributionConfig.GEMFIRE_PREFIX + "DISK_PAGE_SIZE", 8 << 10);
DiskPage(DiskPosition diskPosition) {
- this.setPosition(diskPosition.oplogId, diskPosition.offset / DISK_PAGE_SIZE);
+ setPosition(diskPosition.oplogId, diskPosition.offset / DISK_PAGE_SIZE);
}
}
@@ -2960,7 +2942,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
* Returns the lock lease value to use for DistributedLock and RegionDistributedLock. -1 is
* supported as non-expiring lock.
*/
- long getLockLeaseForLock() { // package-private to avoid synthetic accessor
+ private long getLockLeaseForLock() { // package-private to avoid synthetic accessor
if (getCache().getLockLease() == -1) {
return -1;
}
@@ -2971,8 +2953,9 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
* Returns the lock timeout value to use for DistributedLock and RegionDistributedLock. -1 is
* supported as a lock that never times out.
*/
- long getLockTimeoutForLock(long time, TimeUnit unit) { // package-private to avoid synthetic
- // accessor
+ private long getLockTimeoutForLock(long time, TimeUnit unit) { // package-private to avoid
+ // synthetic
+ // accessor
if (time == -1) {
return -1;
}
@@ -3022,7 +3005,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
public boolean tryLock() {
try {
ReplyProcessor21.forceSevereAlertProcessing();
- return getLockService().lock(this.key, 0, getLockLeaseForLock());
+ return getLockService().lock(key, 0, getLockLeaseForLock());
} catch (IllegalStateException ex) {
lockCheckReadiness();
throw ex;
@@ -3076,9 +3059,9 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
final boolean gotLock;
if (interruptible) {
gotLock =
- getLockService().lockInterruptibly(this.key, waitInterval, getLockLeaseForLock());
+ getLockService().lockInterruptibly(key, waitInterval, getLockLeaseForLock());
} else {
- gotLock = getLockService().lock(this.key, waitInterval, getLockLeaseForLock());
+ gotLock = getLockService().lock(key, waitInterval, getLockLeaseForLock());
}
if (gotLock) {
return true;
@@ -3132,9 +3115,9 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
public void unlock() {
try {
ReplyProcessor21.forceSevereAlertProcessing();
- getLockService().unlock(this.key);
- if (!DistributedRegion.this.entries.containsKey(this.key)) {
- getLockService().freeResources(this.key);
+ getLockService().unlock(key);
+ if (!entries.containsKey(key)) {
+ getLockService().freeResources(key);
}
} catch (IllegalStateException ex) {
lockCheckReadiness();
@@ -3268,7 +3251,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
VersionedObjectList basicPutAll(final Map<?, ?> map,
final DistributedPutAllOperation putAllOp, final Map<Object, VersionTag> retryVersions) {
- Lock dlock = this.getRegionDistributedLockIfGlobal();
+ Lock dlock = getRegionDistributedLockIfGlobal();
try {
return super.basicPutAll(map, putAllOp, retryVersions);
} finally {
@@ -3281,7 +3264,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
public VersionedObjectList basicRemoveAll(final Collection<Object> keys,
final DistributedRemoveAllOperation removeAllOp, final List<VersionTag> retryVersions) {
- Lock dlock = this.getRegionDistributedLockIfGlobal();
+ Lock dlock = getRegionDistributedLockIfGlobal();
try {
return super.basicRemoveAll(keys, removeAllOp, retryVersions);
} finally {
@@ -3306,7 +3289,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
throw new IllegalStateException(
"Region has not been configured with required roles.");
}
- if (!this.isMissingRequiredRoles) { // should we delete this check?
+ if (!isMissingRequiredRoles) { // should we delete this check?
if (logger.isDebugEnabled()) {
logger.debug("No missing required roles to wait for.");
}
@@ -3314,37 +3297,37 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
if (timeout != 0) { // if timeout is zero then fall through past waits
if (timeout == -1) { // infinite timeout
- while (this.isMissingRequiredRoles) {
+ while (isMissingRequiredRoles) {
checkReadiness();
// bail if distribution has stopped
- this.cache.getCancelCriterion().checkCancelInProgress(null);
- synchronized (this.missingRequiredRoles) {
+ cache.getCancelCriterion().checkCancelInProgress(null);
+ synchronized (missingRequiredRoles) {
// one more check while synced
- if (this.isMissingRequiredRoles) {
+ if (isMissingRequiredRoles) {
if (logger.isDebugEnabled()) {
logger.debug("About to wait for missing required roles.");
}
// TODO an infinite wait here might be a problem...
- this.missingRequiredRoles.wait(); // spurious wakeup ok
+ missingRequiredRoles.wait(); // spurious wakeup ok
}
}
}
} else { // use the timeout
long endTime = System.currentTimeMillis() + timeout;
- while (this.isMissingRequiredRoles) {
+ while (isMissingRequiredRoles) {
checkReadiness();
// bail if distribution has stopped
- this.cache.getCancelCriterion().checkCancelInProgress(null);
- synchronized (this.missingRequiredRoles) {
+ cache.getCancelCriterion().checkCancelInProgress(null);
+ synchronized (missingRequiredRoles) {
// one more check while synced
- if (this.isMissingRequiredRoles) {
+ if (isMissingRequiredRoles) {
long timeToWait = endTime - System.currentTimeMillis();
if (timeToWait > 0) {
if (logger.isDebugEnabled()) {
logger.debug("About to wait up to {} milliseconds for missing required roles.",
timeToWait);
}
- this.missingRequiredRoles.wait(timeToWait); // spurious wakeup ok
+ missingRequiredRoles.wait(timeToWait); // spurious wakeup ok
} else {
break;
}
@@ -3355,10 +3338,10 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
// check readiness again: thread may have been notified at destroy time
checkReadiness();
- if (this.isMissingRequiredRoles) {
+ if (isMissingRequiredRoles) {
// sync on missingRequiredRoles to prevent mods to required role status...
- synchronized (this.missingRequiredRoles) {
- return Collections.unmodifiableSet(new HashSet<>(this.missingRequiredRoles));
+ synchronized (missingRequiredRoles) {
+ return Collections.unmodifiableSet(new HashSet<>(missingRequiredRoles));
}
} else {
return Collections.emptySet();
@@ -3376,7 +3359,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
// since we are playing the role
return true;
}
- for (DistributedMember member : this.distAdvisor.adviseGeneric()) {
+ for (DistributedMember member : distAdvisor.adviseGeneric()) {
Set<Role> roles = member.getRoles();
if (roles.contains(role)) {
return true;
@@ -3387,8 +3370,8 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
public void remoteRegionInitialized(CacheProfile profile) {
- synchronized (this.advisorListener) {
- if (this.advisorListener.members == null && hasListener()) {
+ synchronized (advisorListener) {
+ if (advisorListener.members == null && hasListener()) {
Object callback = TEST_HOOK_ADD_PROFILE ? profile : null;
RegionEventImpl event = new RegionEventImpl(this, Operation.REGION_CREATE, callback, true,
profile.peerMemberId);
@@ -3416,17 +3399,18 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
* @since GemFire 5.0
*/
protected class AdvisorListener implements MembershipListener {
- Set members = new HashSet(); // package-private to avoid synthetic accessor
+ Set<InternalDistributedMember> members = new HashSet<>(); // package-private to avoid synthetic
+ // accessor
protected boolean destroyed = false;
- synchronized void addMembers(Set newMembers) {
- this.members.addAll(newMembers);
+ synchronized void addMembers(Set<InternalDistributedMember> newMembers) {
+ members.addAll(newMembers);
}
- protected synchronized Set getInitialMembers() {
- Set initMembers = this.members;
- this.members = null;
+ protected synchronized Set<InternalDistributedMember> getInitialMembers() {
+ Set<InternalDistributedMember> initMembers = members;
+ members = null;
return initMembers;
}
@@ -3445,31 +3429,31 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
/** called when membership listeners are added after region creation */
synchronized void initRMLWrappers() {
Set<InternalDistributedMember> membersWithThisRegion =
- DistributedRegion.this.distAdvisor.adviseGeneric();
+ distAdvisor.adviseGeneric();
initPostCreateRegionMembershipListeners(membersWithThisRegion);
}
@Override
public synchronized void memberJoined(DistributionManager distributionManager,
InternalDistributedMember id) {
- if (this.destroyed) {
+ if (destroyed) {
return;
}
- if (this.members != null) {
- this.members.add(id);
+ if (members != null) {
+ members.add(id);
}
// bug #44684 - do not notify listener of create until remote member is initialized
if (getMembershipAttributes().hasRequiredRoles()) {
// newlyAcquiredRoles is used for intersection and RoleEvent
- Set newlyAcquiredRoles = Collections.emptySet();
+ Set<Role> newlyAcquiredRoles = Collections.emptySet();
synchronized (missingRequiredRoles) {
if (isMissingRequiredRoles) {
- Set roles = id.getRoles();
- newlyAcquiredRoles = new HashSet(missingRequiredRoles);
+ Set<Role> roles = id.getRoles();
+ newlyAcquiredRoles = new HashSet<>(missingRequiredRoles);
newlyAcquiredRoles.retainAll(roles); // find the intersection
if (!newlyAcquiredRoles.isEmpty()) {
missingRequiredRoles.removeAll(newlyAcquiredRoles);
- if (this.members == null && missingRequiredRoles.isEmpty()) {
+ if (members == null && missingRequiredRoles.isEmpty()) {
isMissingRequiredRoles = false;
getCachePerfStats().incReliableRegionsMissing(-1);
if (getMembershipAttributes().getLossAction().isAllAccess())
@@ -3481,17 +3465,17 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
boolean async = resumeReliability(id, newlyAcquiredRoles);
if (async) {
- this.destroyed = true;
+ destroyed = true;
}
}
}
}
- if (!this.destroyed) {
+ if (!destroyed) {
// any number of threads may be waiting on missingRequiredRoles
missingRequiredRoles.notifyAll();
}
}
- if (!this.destroyed && this.members == null && hasListener()) {
+ if (!destroyed && members == null && hasListener()) {
if (!newlyAcquiredRoles.isEmpty()) {
// fire afterRoleGain event
RoleEventImpl relEvent = new RoleEventImpl(DistributedRegion.this,
@@ -3505,13 +3489,13 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
@Override
public synchronized void memberDeparted(DistributionManager distributionManager,
InternalDistributedMember id, boolean crashed) {
- if (this.destroyed) {
+ if (destroyed) {
return;
}
- if (this.members != null) {
- this.members.remove(id);
+ if (members != null) {
+ members.remove(id);
}
- if (this.members == null && hasListener()) {
+ if (members == null && hasListener()) {
RegionEventImpl event =
new RegionEventImpl(DistributedRegion.this, Operation.REGION_CLOSE, null, true, id);
if (crashed) {
@@ -3525,41 +3509,41 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
}
if (getMembershipAttributes().hasRequiredRoles()) {
- Set newlyMissingRoles = Collections.emptySet();
+ Set<Role> newlyMissingRoles = Collections.emptySet();
synchronized (missingRequiredRoles) {
- Set roles = id.getRoles();
- for (Iterator iter = roles.iterator(); iter.hasNext();) {
- Role role = (Role) iter.next();
+ Set<Role> roles = id.getRoles();
+ for (Role role : roles) {
if (getMembershipAttributes().getRequiredRoles().contains(role)
&& !basicIsRoleInRegionMembership(role)) {
- if (newlyMissingRoles == Collections.emptySet()) {
- newlyMissingRoles = new HashSet();
+ if (newlyMissingRoles.isEmpty()) {
+ newlyMissingRoles = new HashSet<>();
}
newlyMissingRoles.add(role);
- if (this.members == null && !isMissingRequiredRoles) {
+ if (members == null && !isMissingRequiredRoles) {
isMissingRequiredRoles = true;
getCachePerfStats().incReliableRegionsMissing(1);
- if (getMembershipAttributes().getLossAction().isAllAccess())
+ if (getMembershipAttributes().getLossAction().isAllAccess()) {
getCachePerfStats().incReliableRegionsMissingFullAccess(1); // rahul
- else if (getMembershipAttributes().getLossAction().isLimitedAccess())
+ } else if (getMembershipAttributes().getLossAction().isLimitedAccess()) {
getCachePerfStats().incReliableRegionsMissingLimitedAccess(1);
- else if (getMembershipAttributes().getLossAction().isNoAccess())
+ } else if (getMembershipAttributes().getLossAction().isNoAccess()) {
getCachePerfStats().incReliableRegionsMissingNoAccess(1);
+ }
boolean async = lostReliability(id, newlyMissingRoles);
if (async) {
- this.destroyed = true;
+ destroyed = true;
}
}
}
}
- if (!this.destroyed) {
+ if (!destroyed) {
missingRequiredRoles.addAll(newlyMissingRoles);
// any number of threads may be waiting on missingRequiredRoles...
missingRequiredRoles.notifyAll();
}
}
- if (!this.destroyed && this.members == null && hasListener()) {
+ if (!destroyed && members == null && hasListener()) {
if (!newlyMissingRoles.isEmpty()) {
// fire afterRoleLoss event
RoleEventImpl relEvent = new RoleEventImpl(DistributedRegion.this,
@@ -3578,15 +3562,15 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
*/
@Override
public DistributedMember getOwnerForKey(KeyInfo key) {
- assert !this.isInternalRegion() || this.isMetaRegionWithTransactions();
- if (!this.getAttributes().getDataPolicy().withStorage() || (this.getConcurrencyChecksEnabled()
- && this.getAttributes().getDataPolicy() == DataPolicy.NORMAL)) {
+ assert !isInternalRegion() || isMetaRegionWithTransactions();
+ if (!getAttributes().getDataPolicy().withStorage() || (getConcurrencyChecksEnabled()
+ && getAttributes().getDataPolicy() == DataPolicy.NORMAL)) {
// execute on random replicate
return getRandomReplicate();
}
// if we are non-persistent, forward transactions to
// a persistent member
- if (this.getConcurrencyChecksEnabled() && !generateVersionTag) {
+ if (getConcurrencyChecksEnabled() && !generateVersionTag) {
return getRandomPersistentReplicate();
}
return super.getOwnerForKey(key);
@@ -3609,8 +3593,8 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
return executeLocally(execution, function, args, 0, rc, filter, sender);
}
return executeOnReplicate(execution, function, args, rc, filter, target);
- } else if (this.getAttributes().getDataPolicy().withReplication()
- || this.getAttributes().getDataPolicy().withPreloaded()) {
+ } else if (getAttributes().getDataPolicy().withReplication()
+ || getAttributes().getDataPolicy().withPreloaded()) {
// execute locally
final Set<InternalDistributedMember> singleMember = Collections.singleton(getMyId());
execution.validateExecution(function, singleMember);
@@ -3632,12 +3616,12 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
private ResultCollector executeOnReplicate(final DistributedRegionFunctionExecutor execution,
final Function function, final Object args, ResultCollector rc, final Set filter,
final DistributedMember target) {
- final Set singleMember = Collections.singleton(target);
+ final Set<InternalDistributedMember> singleMember =
+ Collections.singleton((InternalDistributedMember) target);
execution.validateExecution(function, singleMember);
execution.setExecutionNodes(singleMember);
- HashMap<InternalDistributedMember, Object> memberArgs =
- new HashMap<InternalDistributedMember, Object>();
+ HashMap<InternalDistributedMember, Object> memberArgs = new HashMap<>();
memberArgs.put((InternalDistributedMember) target,
execution.getArgumentsForMember(target.getId()));
@@ -3645,7 +3629,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
execution.getServerResultSender());
DistributedRegionFunctionResultWaiter waiter =
- new DistributedRegionFunctionResultWaiter(this.getSystem(), this.getFullPath(), rc,
+ new DistributedRegionFunctionResultWaiter(getSystem(), getFullPath(), rc,
function, filter, Collections.singleton(target), memberArgs, resultSender);
rc = waiter.getFunctionResultFrom(Collections.singleton(target), function, execution);
@@ -3674,9 +3658,9 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
private int randIndex = -1;
- public GetRandomReplicate() {}
+ GetRandomReplicate() {}
- public GetRandomReplicate(boolean onlyPersistent) {
+ GetRandomReplicate(boolean onlyPersistent) {
this.onlyPersistent = onlyPersistent;
}
@@ -3684,8 +3668,8 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
public boolean visit(DistributionAdvisor advisor, Profile profile, int profileIndex,
int numProfiles, DistributedMember member) {
final CacheProfile cp = (CacheProfile) profile;
- if (this.randIndex < 0) {
- this.randIndex = PartitionedRegion.RANDOM.nextInt(numProfiles);
+ if (randIndex < 0) {
+ randIndex = PartitionedRegion.RANDOM.nextInt(numProfiles);
}
if (cp.dataPolicy.withReplication() && cp.regionInitialized) {
if (onlyPersistent && !cp.dataPolicy.withPersistence()) {
@@ -3695,9 +3679,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
// there may be no replicated node after "randIndex" in which case the
// last visited member will be used
this.member = cp.getDistributedMember();
- if (profileIndex >= this.randIndex) {
- return false;
- }
+ return profileIndex < randIndex;
}
return true;
}
@@ -3706,7 +3688,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
/**
* @return a random replicate, null if there are none
*/
- public InternalDistributedMember getRandomReplicate() {
+ private InternalDistributedMember getRandomReplicate() {
/*
* [sumedh] The old code causes creation of a unnecessary HashSet and population with all
* replicates (which may be large), then copy into an array and then selection of a random one
@@ -3716,16 +3698,16 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
* Random().nextInt(replicates.size())]);
*/
final GetRandomReplicate getReplicate = new GetRandomReplicate();
- this.getCacheDistributionAdvisor().accept(getReplicate, null);
+ getCacheDistributionAdvisor().accept(getReplicate, null);
return getReplicate.member;
}
/**
* @return a random persistent replicate, null if there is none
*/
- public InternalDistributedMember getRandomPersistentReplicate() {
+ private InternalDistributedMember getRandomPersistentReplicate() {
final GetRandomReplicate getPersistentReplicate = new GetRandomReplicate(true);
- this.getCacheDistributionAdvisor().accept(getPersistentReplicate, null);
+ getCacheDistributionAdvisor().accept(getPersistentReplicate, null);
return getPersistentReplicate.member;
}
@@ -3764,15 +3746,17 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
}
- ResultCollector executeLocally(final DistributedRegionFunctionExecutor execution,
- final Function function, final Object args, int prid, final ResultCollector rc,
- final Set filter, final ServerToClientFunctionResultSender sender) {
+ private ResultCollector executeLocally(final DistributedRegionFunctionExecutor execution,
+ final Function function, final Object args, int prid,
+ final ResultCollector rc,
+ final Set filter,
+ final ServerToClientFunctionResultSender sender) {
final LocalResultCollector<?, ?> localRC = execution.getLocalResultCollector(function, rc);
final DistributionManager dm = getDistributionManager();
final DistributedRegionFunctionResultSender resultSender =
new DistributedRegionFunctionResultSender(dm, localRC, function, sender);
final RegionFunctionContextImpl context = new RegionFunctionContextImpl(cache, function.getId(),
- DistributedRegion.this, args, filter, null, null, resultSender, execution.isReExecute());
+ this, args, filter, null, null, resultSender, execution.isReExecute());
execution.executeFunctionOnLocalNode(function, context, resultSender, dm, isTX());
return localRC;
}
@@ -3799,9 +3783,9 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
if (logger.isDebugEnabled()) {
logger.debug("DR: removing member {} from critical member list", member);
}
- synchronized (this.memoryThresholdReachedMembers) {
- this.memoryThresholdReachedMembers.remove(member);
- if (this.memoryThresholdReachedMembers.isEmpty()) {
+ synchronized (memoryThresholdReachedMembers) {
+ memoryThresholdReachedMembers.remove(member);
+ if (memoryThresholdReachedMembers.isEmpty()) {
setMemoryThresholdReached(false);
}
}
@@ -3822,11 +3806,11 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
* @param idm member whose threshold has been exceeded
*/
protected void addCriticalMember(final DistributedMember idm) {
- synchronized (this.memoryThresholdReachedMembers) {
- if (this.memoryThresholdReachedMembers.isEmpty()) {
+ synchronized (memoryThresholdReachedMembers) {
+ if (memoryThresholdReachedMembers.isEmpty()) {
setMemoryThresholdReached(true);
}
- this.memoryThresholdReachedMembers.add(idm);
+ memoryThresholdReachedMembers.add(idm);
}
}
@@ -3837,7 +3821,7 @@ public class DistributedRegion extends LocalRegion implements InternalDistribute
}
synchronized (memoryThresholdReachedMembers) {
... 1391 lines suppressed ...