Revision created by MOE tool push_codebase.
[gae.git] / java / src / main / com / google / appengine / api / LifecycleManager.java
blobffc3b27886e7bd1d3232c856311dd51cd16bba2a
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());
22 private boolean shuttingDown = false;
23 private long deadline = -1L;
25 private LifecycleManager() { }
27 public static LifecycleManager getInstance() {
28 return instance;
31 public boolean isShuttingDown() {
32 return shuttingDown;
35 /**
36 * Register a ShutdownHook to be called when the runtime shuts down.
38 public synchronized void setShutdownHook(ShutdownHook hook) {
39 hooks.put(currentAppVersionId(), hook);
42 /**
43 * Calls Thread.interrupt() on all threads running requests for this
44 * application.
46 public void interruptAllRequests() {
47 AccessController.doPrivileged(
48 new PrivilegedAction() {
49 public Object run() {
50 List<Thread> threads = ApiProxy.getRequestThreads();
51 if (threads != null) {
52 for (Thread thread : threads) {
53 thread.interrupt();
56 return null;
58 });
61 /**
62 * If the runtime is shutting down, returns how long, in
63 * milliseconds, is left for shutdown code to clean up. Otherwise,
64 * returns -1.
66 public long getRemainingShutdownTime() {
67 if (deadline == -1L) {
68 return -1L;
69 } else {
70 return deadline - System.currentTimeMillis();
74 /**
75 * For testing purposes only:
76 * Notifies the LifecycleManager that the runtime is shutting down.
78 public synchronized void beginShutdown(long deadline) {
79 this.shuttingDown = true;
80 this.deadline = deadline;
81 ShutdownHook hook = hooks.get(currentAppVersionId());
82 if (hook != null) {
83 hook.shutdown();
87 private String currentAppVersionId() {
88 ApiProxy.Environment env = ApiProxy.getCurrentEnvironment();
89 return env.getAppId() + "/" + env.getVersionId();
92 private Map<String, ShutdownHook> hooks = new HashMap<String, ShutdownHook>();
94 public interface ShutdownHook {
95 public void shutdown();