1 /* 2 * Geario - A cross-platform abstraction library with asynchronous I/O. 3 * 4 * Copyright (C) 2021-2022 Kerisy.com 5 * 6 * Website: https://www.kerisy.com 7 * 8 * Licensed under the Apache-2.0 License. 9 * 10 */ 11 12 module geario.util.Lifecycle; 13 14 import core.atomic; 15 16 17 import geario.logging; 18 19 /** 20 * A common interface defining methods for start/stop lifecycle control. 21 * The typical use case for this is to control asynchronous processing. 22 */ 23 interface Lifecycle { 24 /** 25 * Start this component. 26 * <p>Should not throw an exception if the component is already running. 27 * <p>In the case of a container, this will propagate the start signal to all 28 * components that apply. 29 */ 30 void Start(); 31 32 /** 33 * Stop this component, typically in a synchronous fashion, such that the component is 34 * fully stopped upon return of this method. 35 */ 36 void Stop(); 37 38 39 /** 40 * Check whether this component is currently running. 41 * @return whether the component is currently running 42 */ 43 bool IsRunning(); 44 } 45 46 47 abstract class AbstractLifecycle : Lifecycle { 48 49 protected shared bool _isRunning; 50 51 this() { 52 53 } 54 55 bool IsRunning() { 56 return _isRunning; 57 } 58 59 bool IsStopped() { 60 return !_isRunning; 61 } 62 63 void Start() { 64 if (cas(&_isRunning, false, true)) { 65 Initialize(); 66 } else { 67 version(GEAR_DEBUG) log.warn("Starting repeatedly!"); 68 } 69 } 70 71 void Stop() { 72 if (cas(&_isRunning, true, false)) { 73 Destroy(); 74 } else { 75 version(GEAR_DEBUG) log.warn("Stopping repeatedly!"); 76 } 77 } 78 79 abstract protected void Initialize(); 80 81 abstract protected void Destroy(); 82 }