Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3850608
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T17:02:09+00:00 2026-05-19T17:02:09+00:00

Is there any way to implement a type of reference whose value can be

  • 0

Is there any way to implement a type of reference whose value can be exchanged with another atomically?


In Java we have AtomicReference which can be swapped with a local variable but not with another AtomicReference.

You can do:

AtomicReference r1 = new AtomicReference("hello");
AtomicReference r2 = new AtomicReference("world");

and swap them with a combination of two operations:

r1.set(r2.getAndSet(r1.get()));

But this leaves them in an inconsistent state in between, where both contain "hello". Also even if you could swap them atomically, you still could not read them (as a pair) atomically.


What I would like to be able to do is:

PairableAtomicReference r1 = new PairableAtomicReference("hello");
PairableAtomicReference r2 = new PairableAtomicReference("world");
AtomicRefPair rp = new AtomicRefPair(r1, r2);

then

Object[] oldVal, newVal;
do {
    oldVal = rp.get();
    newVal = new Object[] {oldVal[1], oldVal[0]};
} while (! rp.compareAndSet(oldVal, newVal));

to swap the values, and in another thread:

AtomicRefPair otherRP = new AtomicRefPair(r1, r2);
System.out.println(Arrays.toString(otherRP.get()));

and be certain that the output will be either [hello, world] or [world, hello].

Notes:

  • r1 and r2 are paired for this operation, but it’s possible that another thread will independently pair, say r1 and another r3 (unfortunately that means I cannot use this solution.)
  • There will be hundreds of thousands of these references, so a global ReentrantLock would be a major bottleneck.
  • rp and otherRP are not necessarily shared between threads, so simply locking them will not work. They could be interned, but the intern pool would need its own synchronization which would be another bottleneck.
  • I have only made groups of 2 references here, but the ability to group 3 or more would be a bonus.

Is it possible to implement a lock-free version of AtomicRefPair? I have a hunch that it isn’t, but if not then maybe there is an article somewhere that explains why?


Related: How do I atomically swap 2 ints in C#?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T17:02:10+00:00Added an answer on May 19, 2026 at 5:02 pm

    I don’t know if there’s a nice solution, but the following ugly one could work:

    public final class MyReference<T> extends ReentrantLock implements Comparable<MyReference<T>> {
        public MyReference() {
            id = counter.incrementAndGet();
        }
    
        public void swap(MyReference<T> other) {
            if (id < other.id) {
                lock();
                other.lock();
            } else {
                other.lock();
                lock();
            }
            final T tmp = value;
            value = other.value;
            other.value = tmp;
            unlock();
            other.unlock();
        }
    
        public static <T> List<T> consistentGet(List<MyReference<T>> references) {
            final ArrayList<MyReference<T>> sortedReferences = Lists.newArrayList(references);
            Collections.sort(sortedReferences);
            for (val r : sortedReferences) r.lock();
            final List<T> result = Lists.newArrayListWithExpectedSize(sortedReferences.size());
            for (val r : references) result.add(r.value);
            for (val r : sortedReferences) r.unlock();
            return result;
        }
    
        @Override
        public int compareTo(MyReference<T> o) {
            return id < o.id ? -1 : id > o.id ? 1 : 0;
        }
    
        private final static AtomicInteger counter = new AtomicInteger();
    
        private T value;
        private final int id;
    }
    
    • Use MyReference instead of AtomicReference.
    • It uses a lot of locks, but none of them is global.
    • It acquires locks in a fixed order, so it’s deadlock-free.
    • It compiles using lombok and guava (take it as pseudocode without them).
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there any way to implement a URL mechanisim in asp.net like it has
is there any way to implement timeout option for individual tests in a bunch
Is there any way to have something that looks just like a file on
Is there any way I can get NHibernate to use the READPAST hint when
Is there any way to check whether a file is locked without using a
Is there any way to capture the MouseDown even from the .NET 2.0 TextBox
Is there any way to apply an attribute to a model file in ASP.NET
Is there any way, in any language, to hook my program when a user
Is there any way to include the SVN repository revision number in the version
Is there any way to use inheritance in database (Specifically in SQL Server 2005)?

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.