1

I have a Spring Boot service that is deployed in multiple instances. I want to have a continuously running "daemon thread" in exactly one of the instances. Should that instance go down, the thread should eventually (after a timeout) become active on some other instance.

The service uses a common MongoDB database, which can in principle provide the locking, but I am looking for a pattern or library that does this properly.

I looked at Shedlock, but it seems to be intended only for short-running jobs with a somewhat predictable duration, instead of long-running daemon threads.

Alex Krauss
  • 9,438
  • 4
  • 27
  • 31

2 Answers2

1

We use Shedlock and I highly recommend it for its simplicity. You say you want to have a long running daemon thread - but could you instead have a @Scheduled(fixedDelay=0) annotated method that would run and then get triggered again to run by Spring as soon as the previous iteration has finished? You would use that as your "while" loop, instead of a single method that has a never ending while loop inside.

Michael
  • 556
  • 3
  • 12
  • Would that guarantee that each invocation of the method would be in the same service instance (thus preserving internal state), until that instance fails? Or could it lead to the "active" instance fluctuating arbitrarily? – Alex Krauss Jul 11 '21 at 23:20
  • You're right, it would run on a random instance. But that's also what allows it to satisfy the requirement "Should that instance go down, the thread should eventually (after a timeout) become active on some other instance." – Michael Jul 12 '21 at 15:02
1

I am currently working on LockExtender that would allow to extend the active lock. Would it help with your use case? The usage would be

LockExtender.extendActiveLock(Duration.of(5, MINUTES), ZERO);
Lukas
  • 13,606
  • 9
  • 31
  • 40
  • That could indeed work, as long as I can ensure that the lock is extended like this on a regular basis. Do I read this correctly as "extend the lock for another 5 minutes"? What is the second parameter? – Alex Krauss Jul 11 '21 at 23:26
  • The second parameter is lockAtLeastFor (see the doc). You can try it in just released 4.25.0 version – Lukas Jul 12 '21 at 18:02