本文整理了Java中org.apache.geode.cache.Region.putIfAbsent
方法的一些代码示例,展示了Region.putIfAbsent
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Region.putIfAbsent
方法的具体详情如下:
包路径:org.apache.geode.cache.Region
类名称:Region
方法名:putIfAbsent
[英]If the specified key is not already associated with a value, associate it with the given value. This is equivalent to
if (!map.containsKey(key))
return map.put(key, value);
else
return map.get(key);
except that the action is performed atomically.
ConcurrentMap operations are supported on partitioned and replicated regions and in client caches. They are also supported on non-empty local regions.
Please read the notes on ConcurrentMap operations in the javadoc for Region.
Region allows the value parameter to be null, which will create an invalid entry.
[中]如果指定的键尚未与值关联,请将其与给定值关联。这相当于
if (!map.containsKey(key))
return map.put(key, value);
else
return map.get(key);
,只是操作是以原子方式执行的。
在分区和复制区域以及客户端缓存中支持ConcurrentMap操作。非空本地区域也支持它们。
请阅读javadoc for Region中有关ConcurrentMap操作的说明。
Region允许value参数为null,这将创建无效条目。
代码示例来源:origin: apache/geode
@Override
@SuppressWarnings("unchecked")
public Object putIfAbsent(Object key, Object value) {
return map.putIfAbsent(key, value);
}
代码示例来源:origin: apache/geode
public RedisDataType metaPutIfAbsent(ByteArrayWrapper key, RedisDataType value) {
return this.redisMetaRegion.putIfAbsent(key.toString(), value);
}
代码示例来源:origin: apache/geode
@Override
public Object putIfAbsent(Object key, Object value) {
try {
preOp();
return this.realRegion.putIfAbsent(key, value);
} finally {
postOp();
}
}
代码示例来源:origin: apache/geode
@Override
public <K, V> V putIfAbsent(String regionName, K key, V value) {
security.authorize(DATA, WRITE, regionName, key);
Region<K, V> region = getRegion(regionName);
Object oldValue = region.putIfAbsent(key, value);
return (V) security.postProcess(regionName, key, oldValue);
}
代码示例来源:origin: apache/geode
@Override
public ByteBuffer processStorageCommand(String key, byte[] value, int flags, Cache cache) {
Region<Object, ValueWrapper> r = getMemcachedRegion(cache);
Object oldVal = r.putIfAbsent(key, ValueWrapper.getWrappedValue(value, flags));
String reply = null;
if (oldVal == null) {
reply = Reply.STORED.toString();
} else {
reply = Reply.NOT_STORED.toString();
}
return asciiCharset.encode(reply);
}
代码示例来源:origin: apache/geode
@Test
public void putIfAbsentIsPostProcessed() {
authorize(DATA, WRITE, REGION, "a");
when(region.putIfAbsent(any(), any())).thenReturn("value");
when(security.postProcess(REGION, "a", "value")).thenReturn("spam");
String oldValue = authorizingCache.putIfAbsent(REGION, "a", "b");
verify(region).putIfAbsent("a", "b");
assertEquals("spam", oldValue);
}
代码示例来源:origin: apache/geode
@Test
public void newEntrySucceeds() throws Exception {
when(regionMock.putIfAbsent(TEST_KEY, TEST_VALUE)).thenReturn(null);
Result<RegionAPI.PutIfAbsentResponse> result1 = operationHandler.process(serializationService,
generateTestRequest(), TestExecutionContext.getNoAuthCacheExecutionContext(cacheStub));
assertNull(serializationService.decode(result1.getMessage().getOldValue()));
verify(regionMock).putIfAbsent(TEST_KEY, TEST_VALUE);
verify(regionMock, times(1)).putIfAbsent(any(), any());
}
代码示例来源:origin: apache/geode
@Test
public void existingEntryFails() throws Exception {
when(regionMock.putIfAbsent(TEST_KEY, TEST_VALUE)).thenReturn(1);
Result<RegionAPI.PutIfAbsentResponse> result1 = operationHandler.process(serializationService,
generateTestRequest(), TestExecutionContext.getNoAuthCacheExecutionContext(cacheStub));
assertNotNull(serializationService.decode(result1.getMessage().getOldValue()));
verify(regionMock).putIfAbsent(TEST_KEY, TEST_VALUE);
verify(regionMock, times(1)).putIfAbsent(any(), any());
}
代码示例来源:origin: apache/geode
@Test
public void putIfAbsent() {
authorize(DATA, WRITE, REGION, "a");
String oldValue = authorizingCache.putIfAbsent(REGION, "a", "b");
verify(region).putIfAbsent("a", "b");
}
代码示例来源:origin: apache/geode
Object putResult = pr.putIfAbsent(Integer.toString(i), Integer.toString(i));
assertThat(putResult).describedAs("Expected null, but got " + putResult + " for key " + i)
.isNull();
Object putResult = pr.putIfAbsent(Integer.toString(i), Integer.toString(i + 1));
assertThat(putResult).describedAs("for i=" + i).isEqualTo(Integer.toString(i));
assertThat(pr.get(Integer.toString(i))).describedAs("for i=" + i).isEqualTo(
代码示例来源:origin: apache/geode
oldValue = keyRegion.putIfAbsent(index, wrapper);
if (oldValue != null) {
index += pushType == ListDirection.LEFT ? -1 : 1; // Subtract index if left push, add if
代码示例来源:origin: apache/geode
private boolean setNX(Region<ByteArrayWrapper, ByteArrayWrapper> r, Command command,
ByteArrayWrapper key, ByteArrayWrapper valueWrapper, ExecutionHandlerContext context) {
checkAndSetDataType(key, context);
Object oldValue = r.putIfAbsent(key, valueWrapper);
if (oldValue != null) {
command.setResponse(Coder.getNilResponse(context.getByteBufAllocator()));
return false;
} else {
command.setResponse(Coder.getSimpleStringResponse(context.getByteBufAllocator(), SUCCESS));
return true;
}
}
代码示例来源:origin: apache/geode
/**
* Some regions (DataPolicy.NORMAL, for example) don't support concurrent ops such as putIfAbsent.
*/
@Test(expected = UnsupportedOperationException.class)
public void unsupportedOperation() throws Exception {
when(regionMock.putIfAbsent(any(), any())).thenThrow(new UnsupportedOperationException());
Result<RegionAPI.PutIfAbsentResponse> result1 = operationHandler.process(serializationService,
generateTestRequest(), TestExecutionContext.getNoAuthCacheExecutionContext(cacheStub));
assertEquals(BasicTypes.ErrorCode.INVALID_REQUEST,
result1.getErrorMessage().getError().getErrorCode());
}
代码示例来源:origin: apache/geode
@Override
public void addRemoteType(int typeId, PdxType type) {
verifyConfiguration();
TXStateProxy currentState = suspendTX();
Region<Object, Object> r = getIdToType();
try {
if (!r.containsKey(typeId)) {
// This type could actually be for this distributed system,
// so we need to make sure the type is published while holding
// the distributed lock.
lock();
try {
r.putIfAbsent(typeId, type);
} finally {
unlock();
}
}
} finally {
resumeTX(currentState);
}
}
代码示例来源:origin: apache/geode
@Override
public void executeCommand(Command command, ExecutionHandlerContext context) {
List<byte[]> commandElems = command.getProcessedCommand();
Region<ByteArrayWrapper, ByteArrayWrapper> r = context.getRegionProvider().getStringsRegion();
if (commandElems.size() < 3) {
command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ArityDef.SETNX));
return;
}
ByteArrayWrapper key = command.getKey();
checkAndSetDataType(key, context);
byte[] value = commandElems.get(VALUE_INDEX);
Object oldValue = r.putIfAbsent(key, new ByteArrayWrapper(value));
if (oldValue != null)
command.setResponse(Coder.getIntegerResponse(context.getByteBufAllocator(), NOT_SET));
else
command.setResponse(Coder.getIntegerResponse(context.getByteBufAllocator(), SET));
}
代码示例来源:origin: apache/geode
@Override
public void executeCommand(Command command, ExecutionHandlerContext context) {
List<byte[]> commandElems = command.getProcessedCommand();
if (commandElems.size() < 4) {
command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), getArgsError()));
return;
}
ByteArrayWrapper key = command.getKey();
Region<ByteArrayWrapper, ByteArrayWrapper> keyRegion =
getOrCreateRegion(context, key, RedisDataType.REDIS_HASH);
byte[] byteField = commandElems.get(FIELD_INDEX);
ByteArrayWrapper field = new ByteArrayWrapper(byteField);
byte[] value = commandElems.get(VALUE_INDEX);
Object oldValue;
if (onlySetOnAbsent())
oldValue = keyRegion.putIfAbsent(field, new ByteArrayWrapper(value));
else
oldValue = keyRegion.put(field, new ByteArrayWrapper(value));
if (oldValue == null)
command.setResponse(Coder.getIntegerResponse(context.getByteBufAllocator(), NEW_FIELD));
else
command.setResponse(Coder.getIntegerResponse(context.getByteBufAllocator(), EXISTING_FIELD));
}
代码示例来源:origin: apache/geode
@Override
public ByteBuffer processBinaryStorageCommand(Object key, byte[] value, long cas, int flags,
Cache cache, RequestReader request) {
ByteBuffer response = request.getResponse();
Region<Object, ValueWrapper> r = getMemcachedRegion(cache);
ValueWrapper val = ValueWrapper.getWrappedValue(value, flags);
try {
Object oldVal = r.putIfAbsent(key, val);
// set status
if (oldVal == null) {
if (getLogger().fineEnabled()) {
getLogger().fine("added key: " + key);
}
if (isQuiet()) {
return null;
}
response.putShort(POSITION_RESPONSE_STATUS, ResponseStatus.NO_ERROR.asShort());
// set cas
response.putLong(POSITION_CAS, val.getVersion());
} else {
if (getLogger().fineEnabled()) {
getLogger().fine("key: " + key + " not added as is already exists");
}
response.putShort(POSITION_RESPONSE_STATUS, ResponseStatus.KEY_EXISTS.asShort());
}
} catch (Exception e) {
response = handleBinaryException(key, request, response, "add", e);
}
return response;
}
代码示例来源:origin: apache/geode
private void testAllOperations() {
ClientCache clientCache = (ClientCache) cache;
Region<String, String> region =
clientCache.<String, String>createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
.create("internalRegion");
assertFailure(() -> region.create("Object1", "Value1"));
assertFailure(() -> region.put("Object1", "Value1"));
assertFailure(() -> region.putIfAbsent("Object1", "Value1"));
assertFailure(() -> region.get("Object1"));
Map<String, String> map = new HashMap<>();
map.put("Object1", "Value1");
assertFailure(() -> region.putAll(map));
List<String> list = new ArrayList<>();
list.add("Object1");
assertFailure(() -> region.getAll(list));
assertFailure(() -> region.removeAll(list));
assertFailure(() -> region.destroy("Object1"));
assertFailure(() -> region.remove("Object1"));
assertFailure(() -> region.replace("Object1", "oldValue", "newValue"));
assertFailure(() -> region.invalidate("Object1"));
assertFailure(region::keySetOnServer);
assertFailure(() -> region.registerInterest("Object1"));
}
代码示例来源:origin: apache/geode
@Test
public void nullValuePassedThrough() throws Exception {
final RegionAPI.PutIfAbsentRequest request =
RegionAPI.PutIfAbsentRequest.newBuilder().setRegionName(TEST_REGION)
.setEntry(ProtobufUtilities.createEntry(serializationService, TEST_KEY, null)).build();
Result<RegionAPI.PutIfAbsentResponse> response = operationHandler.process(serializationService,
request, TestExecutionContext.getNoAuthCacheExecutionContext(cacheStub));
assertNull(serializationService.decode(response.getMessage().getOldValue()));
verify(regionMock).putIfAbsent(TEST_KEY, null);
}
代码示例来源:origin: apache/geode
@Test
public void nullKeyPassedThrough() throws Exception {
final RegionAPI.PutIfAbsentRequest request = RegionAPI.PutIfAbsentRequest.newBuilder()
.setRegionName(TEST_REGION)
.setEntry(ProtobufUtilities.createEntry(serializationService, null, TEST_VALUE)).build();
Result<RegionAPI.PutIfAbsentResponse> response = operationHandler.process(serializationService,
request, TestExecutionContext.getNoAuthCacheExecutionContext(cacheStub));
assertNull(serializationService.decode(response.getMessage().getOldValue()));
verify(regionMock).putIfAbsent(null, TEST_VALUE);
}
内容来源于网络,如有侵权,请联系作者删除!