title: Running only one background thread in google appengine backend
body: <p>As mentioned in <a href="https://cloud.google.com/appengine/docs/java/modules/#Java_Background_threads" rel="nofollow">documentation</a> I am running a background thread in a backend with 1 instance infinitely for some continuous background processing. </p>
  
  <pre><code>import com.google.appengine.api.ThreadManager;
  import java.util.concurrent.AtomicLong;
  
  AtomicLong counter = new AtomicLong();
  
  Thread thread = ThreadManager.createBackgroundThread(new Runnable() {
    public void run() {
      try {
        while (true) {
          counter.doStuff()
          Thread.sleep(10);
        }
      } catch (InterruptedException ex) {
        throw new RuntimeException("Interrupted in loop:", ex);
      }
    }
  });
  thread.start();
  </code></pre>
  
  <p>I have tied this code to _ah/start endpoint so that it gets executed once the instance is started. However while running in local server I see _ah/start request is coming in multiple times during the runtime and it starts multiple such thread . I need only one thread to exist at a time to reduce contention in my background processing. </p>
  
  <p>Is there any way to catch hold of the existing bg thread and check if its running so that new thread creation can be avoided ?</p>
  
  <p><strong>Update</strong> 
  After uploading this code to cloud I also observed that every time _ah/start is invoked on the backend it spawns a new thread as part of _ah/background endpoint and keeps running . In this way there would be many threads running together if we fail to stop the earlier ones.</p>