This project has retired. For details please refer to its Attic page.
Source code
001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.reef.wake.impl;
020
021import org.apache.reef.wake.Stage;
022
023import java.util.ArrayList;
024import java.util.Collections;
025import java.util.List;
026import java.util.concurrent.atomic.AtomicBoolean;
027import java.util.logging.Level;
028import java.util.logging.Logger;
029
030/**
031 * A manager that manages all the stage.
032 */
033public final class StageManager implements Stage {
034
035  private static final Logger LOG = Logger.getLogger(StageManager.class.getName());
036
037  private static final StageManager INSTANCE = new StageManager();
038
039  private final List<Stage> stages = Collections.synchronizedList(new ArrayList<Stage>());
040  private final AtomicBoolean closed = new AtomicBoolean(false);
041
042  private StageManager() {
043    LOG.log(Level.FINE, "StageManager adds a shutdown hook");
044    Runtime.getRuntime().addShutdownHook(new Thread(
045        new Runnable() {
046          @Override
047          public void run() {
048            try {
049              LOG.log(Level.FINEST, "Shutdown hook : closing stages");
050              StageManager.instance().close();
051              LOG.log(Level.FINEST, "Shutdown hook : closed stages");
052            } catch (final Exception ex) {
053              LOG.log(Level.WARNING, "StageManager close failure", ex);
054            }
055          }
056        }
057    ));
058  }
059
060  public static StageManager instance() {
061    return INSTANCE;
062  }
063
064  public void register(final Stage stage) {
065    LOG.log(Level.FINEST, "StageManager adds stage {0}", stage);
066    this.stages.add(stage);
067  }
068
069  @Override
070  public void close() throws Exception {
071    if (this.closed.compareAndSet(false, true)) {
072      for (final Stage stage : this.stages) {
073        LOG.log(Level.FINEST, "Closing {0}", stage);
074        stage.close();
075      }
076    }
077  }
078}