Persistent data structures in Java

前端 未结 8 1314
轻奢々
轻奢々 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 name;
        private AtomicReference
    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?

提交回复
热议问题