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