이 콘텐츠는 선택한 언어로 제공되지 않습니다.

Chapter 15. Clustered Locks


Clustered locks are data structures that are distributed and shared across nodes in a Red Hat JBoss Data Grid cluster. Clustered locks allow you to run code that is synchronized between the nodes in a cluster.

15.1. The Lock API

The lock API consists of the following:

  • EmbeddedClusteredLockManagerFactory initializes a clustered lock manager from an embedded cache manager.
  • ClusteredLockManager provides methods to define, configure, retrieve, and remove clustered locks.
  • ClusteredLock provides methods to implement clustered locks.
Note

Clustered locks are available in Red Hat JBoss Data Grid embedded mode only.

15.2. Supported Configuration

As of this release, Red Hat JBoss Data Grid supports NODE ownership and non-reentrant clustered locks.

NODE ownership allows all nodes in the Red Hat JBoss Data Grid cluster to use a lock.

Reentrant locks allow the node that owns the lock to acquire it again while the node has ownership of the lock. Non-reentrant locks allow any node to acquire the lock. As a result, if two consecutive lock calls are sent for the same owner, the first call acquires the lock if it is available and the second call is blocked.

15.3. Adding Maven Dependencies

To start using clustered locks, add the following dependency to pom.xml:

pom.xml

<dependency>
   <groupId>org.infinispan</groupId>
   <artifactId>infinispan-clustered-lock</artifactId>
   <version>...</version> <!-- 7.2.0 or later -->
</dependency>

15.4. Using Clustered Locks

The following code sample illustrates how to use clustered locks:

// Set up a clustered cache manager.
GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder();

// Configure the cache mode as distributed and synchronous.
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.clustering().cacheMode(CacheMode.DIST_SYNC);

// Initialize a new default cache manager.
DefaultCacheManager cm = new DefaultCacheManager(global.build(), builder.build());

// Initialize a clustered lock manager from the cache manager.
ClusteredLockManager clm1 = EmbeddedClusteredLockManagerFactory.from(cm);

// Define a clustered lock named 'lock' with the default configuration.
clm1.defineLock("lock");

// Get a lock from each node in the cluster.
ClusteredLock lock = clm1.get("lock");

AtomicInteger counter = new AtomicInteger(0);

// Acquire the lock as follows.
// Each 'lock.tryLock(1, TimeUnit.SECONDS)'' method attempts to acquire the lock.
// If the lock is not available, the method waits for the timeout period to elapse. When the lock is acquired, other calls to acquire the lock are blocked until the lock is released.
CompletableFuture<Boolean> call1 = lock.tryLock(1, TimeUnit.SECONDS).whenComplete((r, ex) -> {
    if (r) {
        System.out.println("lock is acquired by the call 1");
        lock.unlock().whenComplete((nil, ex2) -> {
            System.out.println("lock is released by the call 1");
            counter.incrementAndGet();
        });
    }
});

CompletableFuture<Boolean> call2 = lock.tryLock(1, TimeUnit.SECONDS).whenComplete((r, ex) -> {
    if (r) {
        System.out.println("lock is acquired by the call 2");
        lock.unlock().whenComplete((nil, ex2) -> {
            System.out.println("lock is released by the call 2");
            counter.incrementAndGet();
        });
    }
});

CompletableFuture<Boolean> call3 = lock.tryLock(1, TimeUnit.SECONDS).whenComplete((r, ex) -> {
    if (r) {
        System.out.println("lock is acquired by the call 3");
        lock.unlock().whenComplete((nil, ex2) -> {
            System.out.println("lock is released by the call 3");
            counter.incrementAndGet();
        });
    }
});

CompletableFuture.allOf(call1, call2, call3).whenComplete((r, ex) -> {
    // Print the value of the counter.
    System.out.println("Value of the counter is " + counter.get());

    // Stop the cache manager.
    cm.stop();
});
Red Hat logoGithubRedditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

© 2024 Red Hat, Inc.