22
33import java .sql .SQLException ;
44import java .util .Optional ;
5+
56import javax .sql .DataSource ;
6- import net .javacrumbs .shedlock .core .LockConfiguration ;
7- import net .javacrumbs .shedlock .core .LockProvider ;
8- import net .javacrumbs .shedlock .core .SimpleLock ;
9- import net .javacrumbs .shedlock .support .Utils ;
10- import org .slf4j .Logger ;
11- import org .slf4j .LoggerFactory ;
127
138/**
149 * @author Kirill Kurdyukov
@@ -31,33 +26,30 @@ public Optional<SimpleLock> lock(LockConfiguration lockConfiguration) {
3126 try {
3227 connection .setAutoCommit (false );
3328
34- var selectPS = connection .prepareStatement ("SELECT locked_by, lock_until FROM shedlock " +
35- "WHERE name = ? AND lock_until > CurrentUtcTimestamp()" );
36-
37- selectPS .setString (1 , lockConfiguration .getName ());
38-
39- try (var rs = selectPS .executeQuery ()) {
40- if (rs .next ()) {
41- LOGGER .debug ("Instance[{}] acquire lock is failed. Leader is {}, lock_until = {}" ,
42- LOCKED_BY , rs .getString (1 ), rs .getString (2 ));
43- return Optional .empty ();
29+ try (var selectPS = connection .prepareStatement ("SELECT locked_by, lock_until FROM shedlock " +
30+ "WHERE name = ? AND lock_until > CurrentUtcTimestamp()" )) {
31+ selectPS .setString (1 , lockConfiguration .getName ());
32+ try (var rs = selectPS .executeQuery ()) {
33+ if (rs .next ()) {
34+ LOGGER .debug ("Instance[{}] acquire lock is failed. Leader is {}, lock_until = {}" ,
35+ LOCKED_BY , rs .getString (1 ), rs .getString (2 ));
36+ return Optional .empty ();
37+ }
4438 }
4539 }
4640
47- var upsertPS = connection .prepareStatement ("" +
41+ try ( var upsertPS = connection .prepareStatement ("" +
4842 "UPSERT INTO shedlock(name, lock_until, locked_at, locked_by) " +
4943 "VALUES (?, Unwrap(CurrentUtcTimestamp() + ?), CurrentUtcTimestamp(), ?)"
50- );
51-
52- upsertPS .setObject (1 , lockConfiguration .getName ());
53- upsertPS .setObject (2 , lockConfiguration . getLockAtMostFor () );
54- upsertPS .setObject ( 3 , LOCKED_BY );
55- upsertPS . execute ();
44+ )) {
45+ upsertPS . setObject ( 1 , lockConfiguration . getName ());
46+ upsertPS .setObject (2 , lockConfiguration .getLockAtMostFor ());
47+ upsertPS .setObject (3 , LOCKED_BY );
48+ upsertPS .execute ( );
49+ }
5650
5751 connection .commit ();
58-
5952 LOGGER .debug ("Instance[{}] is leader" , LOCKED_BY );
60-
6153 return Optional .of (new YdbJDBCLock (lockConfiguration .getName (), dataSource ));
6254 } finally {
6355 connection .setAutoCommit (autoCommit );
0 commit comments