### Question:
StateMachine { public boolean compareAndSet(T expectedState, T newState) { checkState(!Thread.holdsLock(lock), "Cannot set state while holding the lock"); requireNonNull(expectedState, "expectedState is null"); requireNonNull(newState, "newState is null"); FutureStateChange<T> futureStateChange; ImmutableList<StateChangeListener<T>> stateChangeListeners; synchronized (lock) { if (!state.equals(expectedState)) { return false; } if (state.equals(newState)) { return false; } checkState(!isTerminalState(state), "%s cannot transition from %s to %s", name, state, newState); state = newState; futureStateChange = this.futureStateChange.getAndSet(new FutureStateChange<>()); stateChangeListeners = ImmutableList.copyOf(this.stateChangeListeners); if (isTerminalState(state)) { this.stateChangeListeners.clear(); } } fireStateChanged(newState, futureStateChange, stateChangeListeners); return true; } StateMachine(String name, Executor executor, T initialState);  StateMachine(String name, Executor executor, T initialState, Iterable<T> terminalStates); @SuppressWarnings("FieldAccessNotGuarded") T get(); T set(T newState); T trySet(T newState); boolean setIf(T newState, Predicate<T> predicate); boolean compareAndSet(T expectedState, T newState); ListenableFuture<T> getStateChange(T currentState); void addStateChangeListener(StateChangeListener<T> stateChangeListener); @Override String toString();  }### Answer:
@Test public void testCompareAndSet() throws Exception { StateMachine<State> stateMachine = new StateMachine<>("test", executor, State.BREAKFAST, ImmutableSet.of(State.DINNER)); assertEquals(stateMachine.get(), State.BREAKFAST); assertNoStateChange(stateMachine, () -> stateMachine.compareAndSet(State.DINNER, State.LUNCH)); assertStateChange(stateMachine, () -> stateMachine.compareAndSet(State.BREAKFAST, State.LUNCH), State.LUNCH); assertNoStateChange(stateMachine, () -> stateMachine.compareAndSet(State.BREAKFAST, State.LUNCH)); assertNoStateChange(stateMachine, () -> stateMachine.compareAndSet(State.LUNCH, State.LUNCH)); assertStateChange(stateMachine, () -> stateMachine.compareAndSet(State.LUNCH, State.DINNER), State.DINNER); assertNoStateChange(stateMachine, () -> { try { stateMachine.compareAndSet(State.DINNER, State.LUNCH); fail("expected IllegalStateException"); } catch (IllegalStateException expected) { } }); assertNoStateChange(stateMachine, () -> stateMachine.compareAndSet(State.DINNER, State.DINNER)); }