4141import java .util .List ;
4242
4343/**
44- * A {@link WorldBuilder} that loads the cached world if it exists, or delegates to the
45- * underlying {@link WorldBuilder} otherwise.
44+ * A {@link WorldBuilder} that caches the built World on disk,
45+ * improving performance by loading from cache on subsequent runs.
46+ * <p>
47+ * The cache can be reused when {@link #getWorldCacheHash(Options)} produces
48+ * the same hash value, which is computed based on program input related
49+ * fields in {@link Options}. If any program input related fields change
50+ * in {@link Options}, please update that method accordingly.
51+ * <p>
52+ * Defaults to the {@link #delegate} builder if the cache is unavailable.
4653 */
4754public class CachedWorldBuilder implements WorldBuilder {
4855
4956 private static final Logger logger = LogManager .getLogger (CachedWorldBuilder .class );
5057
5158 private static final String CACHE_DIR = "cache" ;
5259
60+ /**
61+ * The delegate {@link WorldBuilder} used to build the {@link World}
62+ * when the cache is unavailable.
63+ */
5364 private final WorldBuilder delegate ;
5465
5566 public CachedWorldBuilder (WorldBuilder delegate ) {
@@ -59,11 +70,6 @@ public CachedWorldBuilder(WorldBuilder delegate) {
5970
6071 @ Override
6172 public void build (Options options , List <AnalysisConfig > analyses ) {
62- if (!options .isWorldCacheMode ()) {
63- logger .error ("Using CachedWorldBuilder,"
64- + " but world cache mode option is not enabled" );
65- System .exit (-1 );
66- }
6773 File worldCacheFile = getWorldCacheFile (options );
6874 if (loadCache (options , worldCacheFile )) {
6975 return ;
@@ -118,23 +124,13 @@ private void saveCache(File worldCacheFile) {
118124 logger .info ("Saving the world cache to {}" , worldCacheFile );
119125 Timer timer = new Timer ("Save the world cache" );
120126 timer .start ();
121- ObjectOutputStream oos = null ;
122- try {
123- oos = new ObjectOutputStream (
124- new BufferedOutputStream (new FileOutputStream (worldCacheFile )));
127+ try (ObjectOutputStream oos = new ObjectOutputStream (
128+ new BufferedOutputStream (new FileOutputStream (worldCacheFile )))) {
125129 oos .writeObject (World .get ());
126- oos .close ();
127130 } catch (Exception e ) {
128131 logger .error ("Failed to save world cache from {} due to {}" ,
129132 worldCacheFile , e );
130133 } finally {
131- if (oos != null ) {
132- try {
133- oos .close ();
134- } catch (Exception e ) {
135- logger .error ("Failed to close output stream" , e );
136- }
137- }
138134 timer .stop ();
139135 logger .info (timer );
140136 }
0 commit comments