Skip to content

Commit

Permalink
feature:add test
Browse files Browse the repository at this point in the history
  • Loading branch information
lightClouds917 committed Dec 11, 2024
1 parent e63f78e commit 9ce0652
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,13 @@
*/
package org.apache.seata.common.lock;

import org.apache.seata.common.util.CollectionUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.concurrent.ConcurrentHashMap;

import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(MockitoExtension.class)
Expand Down Expand Up @@ -55,6 +58,26 @@ public void testMultipleObtainAndClose() {
assertFalse(resourceLock.isHeldByCurrentThread(), "Lock should be released after second try-with-resources");
}

@Test
public void testResourceLockAutoRemovalFromMap() {
ConcurrentHashMap<String, ResourceLock> lockMap = new ConcurrentHashMap<>();
String key = "testKey";
// Use try-with-resources to obtain and release the lock
try (ResourceLock ignored = CollectionUtils.computeIfAbsent(lockMap, key, k -> new ResourceLock()).obtain()) {
// Do something while holding the lock
assertTrue(lockMap.containsKey(key));
assertTrue(lockMap.get(key).isHeldByCurrentThread());
} finally {
assertFalse(lockMap.get(key).isHeldByCurrentThread());
assertTrue(lockMap.containsKey(key));
// Remove the lock from the map
lockMap.remove(key);
assertFalse(lockMap.containsKey(key));
}
// Ensure the lock is removed from the map
assertFalse(lockMap.containsKey(key));
}

@Test
public void testConcurrentLocking() throws InterruptedException {
ResourceLock resourceLock = new ResourceLock();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ public static LoopContextHolder getCurrent(ProcessContext context, boolean force
DomainConstants.VAR_NAME_CURRENT_LOOP_CONTEXT_HOLDER);

if (null == loopContextHolder && forceCreate) {
try (ResourceLock lock = CollectionUtils.computeIfAbsent(CONTEXT_LOCK_MAP, context, k -> new ResourceLock());
ResourceLock ignored = lock.obtain()) {
try (ResourceLock ignored = CollectionUtils.computeIfAbsent(CONTEXT_LOCK_MAP, context, k -> new ResourceLock()).obtain()) {
loopContextHolder = (LoopContextHolder)context.getVariable(
DomainConstants.VAR_NAME_CURRENT_LOOP_CONTEXT_HOLDER);
if (null == loopContextHolder) {
Expand Down

0 comments on commit 9ce0652

Please sign in to comment.