001    package org.cumulus4j.store.model;
002    
003    import java.util.LinkedList;
004    import java.util.List;
005    
006    public abstract class RunnableManager {
007            private int scopeCounter = 0;
008            private List<Runnable> runnables = new LinkedList<Runnable>();
009    
010            protected RunnableManager() { }
011    
012            public void enterScope() {
013                    ++scopeCounter;
014            }
015    
016            public void exitScope() {
017                    if (--scopeCounter == 0) {
018                            runRunnables();
019                    }
020    
021                    if (scopeCounter < 0)
022                            throw new IllegalStateException("scopeCounter < 0");
023            }
024    
025            protected void assertInScope() {
026                    if (scopeCounter < 1)
027                            throw new IllegalStateException("scopeCounter < 1");
028            }
029    
030            public void addRunnable(Runnable runnable) {
031                    if (runnable == null)
032                            throw new IllegalArgumentException("runnable == null");
033    
034                    runnables.add(runnable);
035            }
036    
037            protected void runRunnables() {
038    //              for (Iterator<Runnable> it = runnables.iterator(); it.hasNext(); ) {
039    //                      Runnable runnable = it.next();
040    //                      it.remove();
041    //                      runnable.run();
042    //              }
043    
044                    // runnables might add other runnables => continue fetching until empty.
045                    while (!runnables.isEmpty()) {
046                            Runnable runnable = runnables.remove(0);
047                            runnable.run();
048                    }
049            }
050    }