Immutable but updated collections?

A common pattern that I come across is the need to update a collection, such as List or HashMap, from a database, but you do not want the values ​​to be added or removed from it between updates.

I recently discovered ImmutableList and ImmutableMap in the Google Guava library, which I really like. But I cannot do "clearAll ()" on these types and not rewrite them. But I like that they are unchanged than this.

So, if I wanted to apply this β€œonly make mutable when updating the database” template, then I probably had to use the volatile variable every time? Or is there a better picture? This can be in a multi-threaded environment, and I would not guarantee the absence of race conditions when updating ();

 public class MarketManager {

     private volatile ImmutableList<Market> markets = null;

     private MarketManager() { 
     }

     public void refresh() { 
         marketList = //build a new immutable market list
     }

     public static MarketManager getInstance() { 
         MarketManager marketManager = new MarketManager();
         marketManager.refresh();
         return marketManager;
     }
}
+4
2

, Collections.unmodifiableList():

public class MarketManager {

     private volatile List<Market> markets = Collections.emptyList();

     private MarketManager() { 
     }

     public void refresh() { 
         marketList = //build a new market list
     }

     public List<Market> getMarkets() {
         return Collections.unmodifiableList(markets);
     }

     // ...
}

Collections.unmodifiableList() List, "" ( ).

+3

, : .

- , . , . , . .

. . , . , .

, , ( ) ( , ​​ ). unmodifiable framework Java, ethe Guava .

+1

All Articles