What is a best design to hold a “global” mutable list?

  softwareengineering

Let’s say that I have an ArrayList of class Person and I have two objects that are generated from two different classes which read and write to this ArrayList.

For example,

public class Main { 
   public static void main(String[] args) { 
       A a = new A();
       B b = new B();
   }
}

What, in your opinion is the best design to handle this ArrayList. I can think about two options:

  1. create the Array List in class Main:

    public class Main { 
       public static ArrayList<Person> list = new ArrayList<>();
    
       public static void main(String[] args) { 
           A a = new A();
           B b = new B();
       }
    }
    

    and then access the list inside classes A and B via Main.list.

  2. Create the ArrayList as a local variable in main method and send to the constructor of A and B.

    public class Main {
        public static void main(String[] args) {
            ArrayList<Person> list = new ArrayList<>(); 
            A a = new A(list);
            B b = new B(list);
        }
    }
    
    public class A { 
        private ArrayList<Person> list;
        public A(ArrayList<Person> list) { 
           this.list = list;
        }
    }
    

    and then list is an attribute of objects A and B.

13

With option 1 your list is actually global mutable state which is usually regarded as a Bad Thing. Passing dependencies to constructors as you do in option 2 is the right thing to do.

There could be issues with your option 2 like concurrency as mentioned by Laiv in a comment, main could not be the best place for this code or you might want to use factories to instantiate A or B to name a few, but you didn’t provide enough context to assess these potential problems. As it is written, option 2 looks fine to me.

5

I’ve seen this handled with a read lock and a write lock. When a write lock is held by one thread, the read lock cannot be obtained by any thread, and no other thread may obtain the write lock. When one thread holds the read lock, other threads may also get the read lock, but no thread may get the write lock. The data can only be mutated when one thread holds the write lock (and by design no threads hold a read lock). This ensures that nobody mutates the data while it is being read. Also, in this scenario, there was only a single thread that was ever able to obtain the write lock. (It was the main UI thread because the data was mutated by the user making changes to the UI.) A similar architecture might work for your scenario.

LEAVE A COMMENT