1.9.30 sync.
[gae.git] / java / src / main / com / google / appengine / api / LifecycleManager.java
blob4036879245b0dcd14a1931c82c09344fe1d4ae6d
1 // Copyright 2010 Google Inc. All Rights Reserved.
3 package com.google.appengine.api;
5 import com.google.apphosting.api.ApiProxy;
7 import java.util.HashMap;
8 import java.util.List;
9 import java.util.Map;
10 import java.util.logging.Logger;
11 import java.security.AccessController;
12 import java.security.PrivilegedAction;
14 /**
15 * Information about the current status of the Java Runtime.
18 public final class LifecycleManager {
20 private static final LifecycleManager instance = new LifecycleManager();
21 private static final Logger log = Logger.getLogger(LifecycleManager.class.getName());
23 private volatile boolean shuttingDown = false;
24 private volatile long deadline = -1L;
26 private LifecycleManager() { }
28 public static LifecycleManager getInstance() {
29 return instance;
32 public boolean isShuttingDown() {
33 return shuttingDown;
36 /**
37 * Register a ShutdownHook to be called when the runtime shuts down.
39 public synchronized void setShutdownHook(ShutdownHook hook) {
40 hooks.put(currentAppVersionId(), hook);
43 /**
44 * Calls Thread.interrupt() on all threads running requests for this
45 * application.
47 public void interruptAllRequests() {
48 AccessController.doPrivileged(
49 new PrivilegedAction() {
50 public Object run() {
51 List<Thread> threads = ApiProxy.getRequestThreads();
52 if (threads != null) {
53 for (Thread thread : threads) {
54 thread.interrupt();
57 return null;
59 });
62 /**
63 * If the runtime is shutting down, returns how long, in
64 * milliseconds, is left for shutdown code to clean up. Otherwise,
65 * returns -1.
67 public long getRemainingShutdownTime() {
68 long value = deadline;
69 if (value == -1L) {
70 return -1L;
71 } else {
72 return value - System.currentTimeMillis();
76 /**
77 * For testing purposes only:
78 * Notifies the LifecycleManager that the runtime is shutting down.
80 public synchronized void beginShutdown(long deadline) {
81 this.shuttingDown = true;
82 this.deadline = deadline;
83 ShutdownHook hook = hooks.get(currentAppVersionId());
84 if (hook != null) {
85 hook.shutdown();
89 private String currentAppVersionId() {
90 ApiProxy.Environment env = ApiProxy.getCurrentEnvironment();
91 return env.getAppId() + "/" + env.getVersionId();
94 private Map<String, ShutdownHook> hooks = new HashMap<String, ShutdownHook>();
96 public interface ShutdownHook {
97 public void shutdown();