How to create a variable that can be set only once but isn't final in Java

后端 未结 12 1590
感情败类
感情败类 2020-12-14 05:43

I want a class that I can create instances of with one variable unset (the id), then initialise this variable later, and have it immutable after initial

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 06:28

    I recently had this problem when writing some code to construct an immutable cyclic graph where edges reference their nodes. I also noticed that none of the existing answers to this question are thread-safe (which actually allows the field to be set more than once), so I thought that I would contribute my answer. Basically, I just created a wrapper class called FinalReference which wraps an AtomicReference and leverages AtomicReference's compareAndSet() method. By calling compareAndSet(null, newValue), you can ensure that a new value is set at most once by multiple concurrently modifying threads. The call is atomic and will only succeed if the existing value is null. See the example source below for FinalReference and the Github link for sample test code to demonstrate correctness.

    public final class FinalReference {
      private final AtomicReference reference = new AtomicReference();
    
      public FinalReference() {
      }
    
      public void set(T value) {
        this.reference.compareAndSet(null, value);
      }
    
      public T get() {
        return this.reference.get();
      }
    }
    

提交回复
热议问题