001 /**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one or more
004 * contributor license agreements. See the NOTICE file distributed with
005 * this work for additional information regarding copyright ownership.
006 * The ASF licenses this file to You under the Apache License, Version 2.0
007 * (the "License"); you may not use this file except in compliance with
008 * 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, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018 package org.apache.camel.impl;
019
020 import java.util.concurrent.atomic.AtomicBoolean;
021
022 import org.apache.camel.Service;
023
024 /**
025 * A useful base class which ensures that a service is only initialized once and provides some helper methods for
026 * enquiring of its status
027 *
028 * @version $Revision: 534063 $
029 */
030 public abstract class ServiceSupport implements Service {
031 private AtomicBoolean started = new AtomicBoolean(false);
032 private AtomicBoolean stopping = new AtomicBoolean(false);
033 private AtomicBoolean stopped = new AtomicBoolean(false);
034
035 public void start() throws Exception {
036 if (started.compareAndSet(false, true)) {
037 doStart();
038 }
039 }
040
041 public void stop() throws Exception {
042 if (stopped.compareAndSet(false, true)) {
043 stopping.set(true);
044 try {
045 doStop();
046 }
047 finally {
048 stopped.set(true);
049 started.set(false);
050 stopping.set(false);
051 }
052 }
053 }
054
055 /**
056 * @return true if this service has been started
057 */
058 public boolean isStarted() {
059 return started.get();
060 }
061
062 /**
063 * @return true if this service is in the process of closing
064 */
065 public boolean isStopping() {
066 return stopping.get();
067 }
068
069
070 /**
071 * @return true if this service is closed
072 */
073 public boolean isStopped() {
074 return stopped.get();
075 }
076
077 protected abstract void doStart() throws Exception;
078
079 protected abstract void doStop() throws Exception;
080
081 }