package de.gurkenlabs.litiengine;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public abstract class UpdateLoop extends Thread implements ILoop {
  private static final Logger log = Logger.getLogger(UpdateLoop.class.getName());
  private final List<IUpdateable> updatables;

  protected UpdateLoop() {
    this.updatables = new CopyOnWriteArrayList<>();
  }

  @Override
  public void run() {
    // nothing to do for now in the base implementation
  }

  @Override
  public void attach(final IUpdateable updatable) {
    if (updatable == null) {
      return;
    }

    if (this.updatables.contains(updatable)) {
      log.log(Level.FINE, "Updatable {0} already registered for update!", new Object[] { updatable });
      return;
    }

    this.updatables.add(updatable);
  }

  @Override
  public void detach(final IUpdateable updatable) {
    this.updatables.remove(updatable);
  }

  protected List<IUpdateable> getUpdatables() {
    return this.updatables;
  }

  protected void update() {
    this.getUpdatables().forEach(updatable -> {
      try {
        if (updatable != null) {
          updatable.update();
        }
      } catch (final Exception e) {
        log.log(Level.SEVERE, e.getMessage(), e);
      }
    });
  }
}

@@ -45,19 +45,48 @@
 va.util.
-Lis
+Collections;%0Aimport java.util.Se
 t;%0Aimpor
@@ -110,34 +110,31 @@
 rrent.Co
-pyOnWriteArrayList
+ncurrentHashMap
 ;%0Aimport
@@ -358,19 +358,18 @@
 e final 
-Lis
+Se
 t%3CIUpdat
@@ -441,36 +441,80 @@
 s = 
-new CopyOnWriteArrayList%3C
+Collections.newSetFromMap(new ConcurrentHashMap%3CIUpdateable, Boolean
 %3E()
+)
 ;%0A  
@@ -1061,11 +1061,10 @@
 ted 
-Lis
+Se
 t%3CIU

Improve the performance of the UpdateLoop by using a concurrent HashSet instead of a CopyOnWriteArrayList.