0

I am working on implementing a very specific health check strategy for my service. Here are the details :

All the application threads update a mutable Spring bean "problemDetectedTimestamp" when they come across a problem.

I have a background thread(implemented using ScheduledExecutorService) running every second which updates another mutable Spring bean "isServiceHealthy" based on the value of "problemDetectedTimestamp". To elaborate, the background thread checks whether the value of "problemDetectedTimestamp" falls in the last thread execution interval. If yes, the "isServiceHealthy" flag is updated to "false". I have some other application logic which is dependent on "isServiceHealthy" flag.

Now, we have multiple threads running and as such, I would want the "problemDetectedTimestamp" to be updated in a thread safe manner without incurring the overhead of using "synchronized" blocks. I am considering declaring "problemDetectedTimestamp" as a volatile variable to ensure that writes from application threads are atomic and my background thread reads it from memory rather than from its local cache. But, I am not sure of how to declare the bean as "volatile" in Spring XML as "volatile" is a concept specific to java/c++ and I am pretty sure Spring is not tighly coupled with java as such.

roger
  • 269
  • 1
  • 5
  • 20
  • Apart from the fact that `isServiceHealthy` is probably not a bean as your post suggests, using `AtomicBoolean` and `AtomicLong` would suffice. – 11thdimension Oct 11 '17 at 14:23
  • "Overhead of using "synchronized" blocks" - Well depends on the type of application you are writing. You cannot always get away without using locks. – Sneh Oct 11 '17 at 14:25
  • @11thdimension Even I was thinking about just keeping problemDetectedTimestamp and isServiceHealthy as AtomicLong and AtomicBoolean respectively. I just figured out that using Atomic* variables gives the properties of "volatile" keyword as well. I just need these 2 variables to represent global state which can be accessed by all my application threads. the only doubt that I have is whether AtomicLong necessarily guarantee thread safety given the memory updates would be made 32 bits at a time and different threads might see different bits. – roger Oct 11 '17 at 14:29
  • Yes, all `Atomic...` classes provide thread safe methods, https://stackoverflow.com/questions/44053300/is-atomic-integer-incrementandget-thread-safe – 11thdimension Oct 11 '17 at 14:48

0 Answers0