Persistent data structures in Java

前端 未结 8 1307
轻奢々
轻奢々 2021-01-30 02:54

Does anyone know a library or some at least some research on creating and using persistent data structures in Java? I don\'t refer to persistence as long term storage but persis

相关标签:
8条回答
  • 2021-01-30 03:28

    Do you want immutability :

    1. so external code cannot change the data?
    2. so once set a value cannot be changed?

    In both cases there are easier ways to accomplish the desired result.

    Stopping external code from changing the data is easy with interfaces:

    public interface Person {
       String getName();
       Address getAddress();
    }
    public interface PersonImplementor extends Person {
       void setName(String name);
       void setAddress(Address address);
    }
    
    public interface Address {
        String getCity();
    }
    
    
    public interface AddressImplementor {
        void setCity(String city);
    }
    

    Then to stop changes to a value once set is also "easy" using java.util.concurrent.atomic.AtomicReference (although hibernate or some other persistence layer usage may need to be modified):

    class PersonImpl implements PersonImplementor {
        private AtomicReference<String> name;
        private AtomicReference<Address> address;
    
        public void setName(String name) {
            if ( !this.name.compareAndSet(name, name) 
               && !this.name.compareAndSet(null, name)) {
                throw new IllegalStateException("name already set to "+this.name.get()+" cannot set to "+name);
            }
        }
        // .. similar code follows....
    }
    

    But why do you need anything more than just interfaces to accomplish the task?

    0 讨论(0)
  • 2021-01-30 03:30

    It is very difficult, if not impossible, to make things immutable that ain't designed so.

    If you can design from ground up:

    • use only final fields
    • do not reference non immutable objects
    0 讨论(0)
提交回复
热议问题