0

I have singleton which holds connection to external service, this connection is declared as atomic reference

Connection connection = new AtomicReference<>(new Connection());

As long as this connection is used by my webservice, many threads may want to access this reference, so if one is using it at the moment, all others will wait.

I want to log information that thread is waiting for this reference, does anybody know how to detect that thread is waiting for atomic reference ?

Should I extend AtomicReference and wrap methods ? Is there any other way ?

Kasper Ziemianek
  • 1,329
  • 8
  • 15
  • " so if one is using it at the moment, all others will wait. ", how is this achieved? AtomicReferences are a non-blocking datastructure, so you will have had to have done something to make that possible. Plus your example is not valid Java, AtomicReference is not of type Connection. – Chris K Jul 18 '14 at 09:38
  • Oh, i see it's atomic only in case of update. Bad assumption... – Kasper Ziemianek Jul 18 '14 at 09:42
  • 1
    @xwid, thats right and then only if using the CAS version of the update methods(compareAndSet). That is, only set the value if it is currently set to the same value as supplied to the call. This [article](http://baptiste-wicht.com/posts/2010/09/java-concurrency-atomic-variables.html) may help you. – Chris K Jul 18 '14 at 09:45

1 Answers1

2

AtomicReferences are a non-blocking concurrency primitive. All readers will be able to instantly dereference it, and only if there are many concurrent writers, and they are using a Compare-and-Swap action to update the reference (not the plain, unconditional set), there will be some stalling, but again not in the form of blocking; instead they will be running their busy write-retry loops. All this writing will still leave the readers uninfluenced.

So, any blocking may occur only on your Connection instance, if it has such blocking implemented. This, of course, is out of scope for any AtomicReference-related concerns.

William F. Jameson
  • 1,833
  • 9
  • 14