001/* 002 * (C) Copyright 2006-2017 Nuxeo (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * bstefanescu 018 */ 019package org.nuxeo.ecm.platform.convert.ooomanager; 020 021import java.util.concurrent.CountDownLatch; 022import java.util.concurrent.TimeUnit; 023 024/** 025 * @author bogdan 026 * @since 9.2 027 */ 028public class OOoState { 029 030 public static final int STOPPED = 0; 031 032 public static final int STARTING = 1; 033 034 public static final int STARTED = 2; 035 036 public static final int STOPPING = 3; 037 038 protected volatile int status = STOPPED; 039 040 protected volatile CountDownLatch startLatch = null; 041 042 public synchronized void update(int state) { 043 if (state == STARTING) { 044 this.startLatch = new CountDownLatch(1); 045 this.status = STARTING; 046 } else { 047 this.status = state; 048 // release latch (usually state is STARTED) 049 if (startLatch != null) { 050 startLatch.countDown(); // release it if not released 051 startLatch = null; 052 } 053 } 054 } 055 056 public int getStatus() { 057 return status; 058 } 059 060 public boolean isStarted() { 061 return status == STARTED; 062 } 063 064 public boolean isStarting() { 065 return status == STARTING; 066 } 067 068 public boolean isStopping() { 069 return status == STOPPING; 070 } 071 072 public boolean isStopped() { 073 return status == STOPPED; 074 } 075 076 /** 077 * Same as {@link #isAlive(long, TimeUnit)} with a 60 seconds timeout 078 */ 079 public boolean isAlive() throws InterruptedException { 080 return isAlive(60, TimeUnit.SECONDS); 081 } 082 083 /** 084 * Tests whether the server is started. If the servers is in starting state then waits until it is fully started If 085 * the server is already started returns true. If it is stopped or stopping returns false. If it is starting then 086 * waits using the given timeout until either the server is started or timeout is reached. Returns true if at the 087 * end of the method the server is started, false otherwise 088 */ 089 public boolean isAlive(long timeout, TimeUnit unit) throws InterruptedException { 090 CountDownLatch latch = startLatch; 091 if (latch != null) { 092 latch.await(timeout, unit); 093 } 094 return status == STARTED; 095 } 096 097}