Revision created by MOE tool push_codebase.
[gae.git] / java / src / main / com / google / appengine / tools / development / InstanceStateHolder.java
blobb6e2474daf9c76f4fa358dacc2d373fd894aaa6e
1 package com.google.appengine.tools.development;
3 import javax.annotation.concurrent.GuardedBy;
5 /**
6 * Holder for the state of a server or backend instance.
7 */
8 public class InstanceStateHolder {
9 static enum InstanceState {
10 INITIALIZING, SLEEPING, RUNNING_START_REQUEST, RUNNING, STOPPED, SHUTDOWN;
12 private final String serverOrBackendName;
13 private final int instance;
14 @GuardedBy("this")
15 private InstanceState currentState = InstanceState.SHUTDOWN;
17 /**
18 * Constructs an {@link InstanceStateHolder}.
20 * @param serverOrBackendName For server instances the server name and for backend instances the
21 * backend name.
22 * @param instance The instance number or -1 for load balancing servers and automatic servers.
24 InstanceStateHolder(String serverOrBackendName, int instance) {
25 this.serverOrBackendName = serverOrBackendName;
26 this.instance = instance;
29 /**
30 * Updates the current server state and verifies that the previous state is
31 * what is expected.
33 * @param newState The new state to change to
34 * @param acceptablePreviousStates Acceptable previous states
35 * @throws IllegalStateException If the current state is not one of the
36 * acceptable previous states
38 synchronized void testAndSet(InstanceState newState,
39 InstanceState... acceptablePreviousStates) throws IllegalStateException {
40 if (test(acceptablePreviousStates)) {
41 currentState = newState;
42 return;
44 StringBuilder error = new StringBuilder();
45 error.append("Tried to change state to " + newState);
46 error.append(" on server " + serverOrBackendName + "." + instance);
47 error.append(" but previous state is not ");
48 for (int i = 0; i < acceptablePreviousStates.length; i++) {
49 error.append(acceptablePreviousStates[i].name() + " | ");
51 throw new IllegalStateException(error.toString());
54 /**
55 * Returns true if current state is one of the provided acceptable states.
57 synchronized boolean test(InstanceState... acceptableStates) {
58 for (InstanceState acceptable : acceptableStates) {
59 if (currentState == acceptable) {
60 return true;
63 return false;
66 /**
67 * Checks if the server is in a state where it can accept incoming requests.
69 * @return true if the server can accept incoming requests, false otherwise.
71 synchronized boolean acceptsConnections() {
72 return (currentState == InstanceState.RUNNING
73 || currentState == InstanceState.RUNNING_START_REQUEST
74 || currentState == InstanceState.SLEEPING);
77 /**
78 * Returns the display name for the current state.
80 synchronized String getDisplayName() {
81 return currentState.name().toLowerCase();
84 /**
85 * Unconditionally sets the state.
87 synchronized void set(InstanceState newState) {
88 currentState = newState;