How to use Shed Lock with H2 database for testing?

Nov 18, 2025

Leave a message

John Lee
John Lee
I’m the chief technology officer at Hunan Lianhu Hardware Co., driving our innovation strategy. My focus is on developing cutting-edge hardware solutions that meet modern demands.

When it comes to testing applications that require distributed locking, Shed Lock is a powerful tool that can be effectively integrated with an H2 database. As a Shed Lock supplier, I've witnessed firsthand the challenges and opportunities that come with implementing and testing such locking mechanisms. In this blog post, I'll guide you through the process of using Shed Lock with an H2 database for testing purposes.

Understanding Shed Lock

Shed Lock is a library that provides distributed locks for scheduled tasks in Java applications. It ensures that a particular task is executed only once across multiple instances of an application, preventing race conditions and other concurrency issues. This is crucial in distributed systems where multiple nodes may attempt to execute the same task simultaneously.

The core concept behind Shed Lock is simple: it uses a database to store lock information. When a task is about to be executed, it tries to acquire a lock in the database. If the lock is available, the task proceeds; otherwise, it waits or skips the execution. This mechanism ensures that only one instance of the task can run at a time.

6-36-4

Why Use H2 Database for Testing?

The H2 database is an in - memory database that is lightweight, fast, and easy to set up. It doesn't require a separate server process, making it ideal for testing environments. When testing Shed Lock, using an H2 database allows you to quickly spin up a testing environment without the overhead of managing a full - fledged database system.

Setting Up the Project

To start using Shed Lock with an H2 database, you first need to set up a Java project. You can use a build tool like Maven or Gradle. Here's an example of how to add the necessary dependencies to a Maven project:

<dependencies>
    <dependency>
        <groupId>net.javacrumbs.shedlock</groupId>
        <artifactId>shedlock-spring</artifactId>
        <version>4.44.0</version>
    </dependency>
    <dependency>
        <groupId>net.javacrumbs.shedlock</groupId>
        <artifactId>shedlock-provider-jdbc-template</artifactId>
        <version>4.44.0</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>2.1.214</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
</dependencies>

Configuring the H2 Database

Once the dependencies are added, you need to configure the H2 database. In a Spring Boot application, you can do this in the application.properties or application.yml file. Here's an example of application.properties:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true

These properties configure the H2 database to run in an in - memory mode. The spring.h2.console.enabled=true property enables the H2 console, which can be useful for debugging.

Configuring Shed Lock

Next, you need to configure Shed Lock to use the H2 database as the lock provider. You can do this by creating a configuration class:

import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbc.template.JdbcTemplateLockProvider;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S")
public class ShedLockConfig {

    @Bean
    public LockProvider lockProvider(DataSource dataSource) {
        return new JdbcTemplateLockProvider(
                JdbcTemplateLockProvider.Configuration.builder()
                       .withJdbcTemplate(new JdbcTemplate(dataSource))
                       .usingDbTime()
                       .build()
        );
    }
}

In this configuration class, we define a LockProvider bean that uses the JdbcTemplateLockProvider with the H2 data source. The @EnableSchedulerLock annotation enables the Shed Lock functionality in the Spring application.

Creating a Scheduled Task

Now, let's create a simple scheduled task that uses Shed Lock. Here's an example:

import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTask {

    @Scheduled(fixedRate = 5000)
    @SchedulerLock(name = "scheduledTask", lockAtMostFor = "PT10S", lockAtLeastFor = "PT5S")
    public void runTask() {
        System.out.println("Task is running...");
    }
}

The @Scheduled annotation defines the schedule for the task, and the @SchedulerLock annotation ensures that the task is executed only once across multiple instances. The name attribute of the @SchedulerLock annotation is used to identify the lock, and the lockAtMostFor and lockAtLeastFor attributes define the maximum and minimum duration for which the lock is held.

Testing the Setup

To test the setup, you can run the Spring Boot application. You should see the task running at the specified interval, and the lock mechanism should ensure that it runs only once. You can also use the H2 console to verify the lock entries in the database.

Advanced Testing Scenarios

In addition to basic testing, you may want to test more advanced scenarios, such as lock expiration, concurrent access, and error handling. You can use testing frameworks like JUnit and Mockito to simulate these scenarios.

For example, you can write a unit test to verify that the lock is released after the lockAtMostFor duration:

import net.javacrumbs.shedlock.core.LockConfiguration;
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.core.SimpleLock;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.time.Duration;
import java.time.Instant;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;

@SpringBootTest
public class LockExpirationTest {

    @Autowired
    private LockProvider lockProvider;

    @Test
    public void testLockExpiration() {
        LockConfiguration lockConfig = new LockConfiguration(Instant.now(), "testLock", Duration.ofSeconds(5));
        SimpleLock lock = lockProvider.lock(lockConfig);
        assertNotNull(lock, "Lock should be acquired");

        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        SimpleLock newLock = lockProvider.lock(lockConfig);
        assertNotNull(newLock, "Lock should be available after expiration");
    }
}

Conclusion

Using Shed Lock with an H2 database for testing is a straightforward and effective way to ensure the correctness of your distributed locking mechanisms. By following the steps outlined in this blog post, you can set up a testing environment quickly and test various scenarios to ensure that your application works as expected.

If you're interested in purchasing Shed Lock solutions or have any questions about integrating Shed Lock with your application, we're here to help. Whether you need Shed Door Locks for physical security or Quarter Turn Lock for specific access control, or even Outdoor Lock for external applications, our team of experts can provide you with the best solutions. Contact us to start a procurement discussion and find the right products for your needs.

References

  • Shed Lock official documentation
  • Spring Boot official documentation
  • H2 database official documentation
Send Inquiry