Over a million developers have joined DZone.

Concurrent Max

·

Can you think of a better way to implement this code?

    private volatile Guid lastEtag;
    private readonly object lastEtagLocker = new object();

    internal void UpdateLastWrittenEtag(Guid? etag)
    {
        if (etag == null)
            return;

        var newEtag = etag.Value.ToByteArray();

        // not the most recent etag
        if (Buffers.Compare(lastEtag.ToByteArray(), newEtag) <= 0)
        {
            return;
        }

        lock (lastEtagLocker)
        {
            // not the most recent etag
            if (Buffers.Compare(lastEtag.ToByteArray(), newEtag) <= 0)
            {
                return;
            }

            lastEtag = etag.Value;
        }
    }

We have multiple threads calling this function, and we need to ensure that lastEtag value is always the maximum value. This has the potential to be called often, so I want to make sure that I chose the best way to do this. Ideas?

Topics:

Published at DZone with permission of Ayende Rahien, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}