Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Concurrent Max

DZone's Guide to

Concurrent Max

· ·
Free Resource

RavenDB vs MongoDB: Which is Better? This White Paper compares the two leading NoSQL Document Databases on 9 features to find out which is the best solution for your next project.  

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?

Do you pay to use your database? What if your database paid you? Learn more with RavenDB.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}