perf[orm]: 在lpmap种增加putIfAbsent

This commit is contained in:
jaysunxiao
2021-08-23 17:32:07 +08:00
parent e79e1f8b74
commit 438ec37095
4 changed files with 80 additions and 1 deletions
@@ -47,6 +47,15 @@ public class ConcurrentFileChannelHeapMap<V extends IPacket> implements LpMap<V>
return concurrentHeapMap.put(key, value);
}
@Override
public V putIfAbsent(long key, V packet) {
var previousValue = concurrentHeapMap.putIfAbsent(key, packet);
if (previousValue == null) {
previousValue = put(key, packet);
}
return previousValue;
}
@Override
public V delete(long key) {
fileChannelLock.lock();
@@ -41,12 +41,29 @@ public class ConcurrentHeapMap<V extends IPacket> implements LpMap<V> {
break;
}
maxIndexAtomic.compareAndExchange(maxIndex, key);
maxIndexAtomic.compareAndSet(maxIndex, key);
}
return map.put(key, value);
}
@Override
public V putIfAbsent(long key, V packet) {
var previousValue = map.putIfAbsent(key, packet);
if (previousValue == null) {
while (true) {
var maxIndex = maxIndexAtomic.get();
if (key <= maxIndex) {
break;
}
maxIndexAtomic.compareAndSet(maxIndex, key);
}
}
return previousValue;
}
@Override
public V delete(long key) {
checkKey(key);
@@ -31,6 +31,14 @@ public interface LpMap<V extends IPacket> {
*/
V put(long key, V packet);
default V putIfAbsent(long key, V packet) {
var v = get(key);
if (v == null) {
v = put(key, packet);
}
return v;
}
/**
* @return 返回被删除的那个值
*/
@@ -0,0 +1,45 @@
/*
* Copyright (C) 2020 The zfoo Authors
* Licensed 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 com.zfoo.orm.lpmap;
import com.zfoo.orm.lpmap.model.MyPacket;
import com.zfoo.protocol.ProtocolManager;
import org.junit.Assert;
import org.junit.Test;
import java.util.Set;
/**
* @author jaysunxiao
* @version 3.0
*/
public class ConcurrentHeapMapTest {
@Test
public void putIfAbsentTest() {
ProtocolManager.initProtocol(Set.of(MyPacket.class));
var myPacket = new MyPacket();
myPacket.setA(1);
var map = new ConcurrentHeapMap<MyPacket>();
var previous1 = map.put(1, myPacket);
var previous2 = map.put(2, myPacket);
var previous3 = map.put(2, new MyPacket());
Assert.assertNull(previous1);
Assert.assertNull(previous2);
Assert.assertEquals(previous3, myPacket);
}
}