All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fi.evolver.basics.spring.lock.LockRepository Maven / Gradle / Ivy

There is a newer version: 6.5.1
Show newest version
package fi.evolver.basics.spring.lock;

import java.time.Duration;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import fi.evolver.basics.spring.lock.entity.Lock;


@Repository
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public interface LockRepository extends JpaRepository {
	static final Logger LOG = LoggerFactory.getLogger(LockRepository.class);

	Optional findByName(String name);


	@Modifying
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	@Query("delete Lock l where l.id = :id")
	int deleteById(long id);


	@Transactional(propagation = Propagation.REQUIRES_NEW)
	default Lock tryTakeLock(String name, Duration maxValidity) {
		Optional oldLock = findByName(name);

		if (oldLock.isPresent()) {
			if (oldLock.get().isValid())
				return null;
			else
				deleteLock(oldLock.get());
		}

		Lock lock = new Lock(name, maxValidity.toMillis());
		saveAndFlush(lock);
		return lock;
	}

	private void deleteLock(Lock lock) {
		LOG.warn("Deleting timed out lock: {}", lock);
		delete(lock);
		flush();
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy