1. 9
  1.  

  2. 8

    To me, this is just bad design. If I were in charge of engineering at Spotify, I would be embarrassed about this blog post. In particular, index is an atomic variable that someone is decrementing. If this is just one thread, it is possible that another thread got the exact same value of index before someone decremented it, and therefore will use the same connection. Therefore, this is not really an implementation of round-robin. A real implementation of round-robin would have a concurrent queue of connections. You could argue that a concurrent queue is unnecessarily slow, but they are only accessing it hundreds of times per second so it would not be a big deal. Why the premature optimization? If something causes the decrementing to happen less often than the request for connections, it could be the case that many threads get the same value of index and contend for the same connection. What happens then?

    Less important: if you’re trying to wrap around and presumably you started with Integer.MAX_VALUE, why do you subtract Integer.MAX_VALUE from index rather than do Integer.MAX_VALUE + index? It would be more readable if nothing else.

    The key takeaway: why get clever and write a crappy, prematurely-optimized implementation of round-robin that doesn’t really work instead of using a concurrent queue and optimize when needed?

    1. 6

      That’s not what is usually called Underflow. https://en.wikipedia.org/wiki/Arithmetic_underflow