1. 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. 4

      I had good results with the “Who’s hiring” thread on Hacker News, but that was three years ago. Lobsters didn’t exist then, and the HN community was smaller.

      1. 1

        I remember reading about this and other common C gotchas many years ago, in Peter Van Der Linden’s Deep C Secrets. It may be outdated today, but back then (the 90s) I found it more useful than the K&R for practical purposes.

        1. 2

          I wanted to tag this as ‘clojure’ but lisp was the closest. I was surprised that clojure is not a tag, given that it’s a pretty popular language.

          1. 1

            Here, Clojure is lumped in with the other Lisps, as it is a Lisp. Common Lisp, Scheme, Clojure – all the same tag.

            1. 2

              This article, however, involves using Clojure type hints to generate an efficient algorithm; it isn’t actually applicable if you are using a Lisp. (Meanwhile, people who like Lisp actually often dislike Clojure, and vice versa, based on the posts I’ve read from a bunch of mailing lists while I was doing due diligence on the language.)

              1. 2

                I see it like I see how C, C++ and Objective C can be lumped together (which makes less sense than the Lisp grouping); most of the time the basic concepts will apply. This is an example of an edge case, and I would personally prefer not have too many categories. My $0.02.