View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.reactor;
29  
30  import java.io.Closeable;
31  import java.io.IOException;
32  import java.nio.channels.ClosedSelectorException;
33  import java.nio.channels.SelectionKey;
34  import java.nio.channels.Selector;
35  import java.util.Date;
36  import java.util.Queue;
37  import java.util.Set;
38  import java.util.concurrent.atomic.AtomicReference;
39  
40  import org.apache.hc.core5.io.CloseMode;
41  import org.apache.hc.core5.io.Closer;
42  import org.apache.hc.core5.util.Args;
43  import org.apache.hc.core5.util.TimeValue;
44  
45  abstract class AbstractSingleCoreIOReactor implements IOReactor {
46  
47      private final Queue<ExceptionEvent> auditLog;
48      private final AtomicReference<IOReactorStatus> status;
49      private final Object shutdownMutex;
50  
51      final Selector selector;
52  
53      AbstractSingleCoreIOReactor(final Queue<ExceptionEvent> auditLog) {
54          super();
55          this.auditLog = auditLog;
56          this.shutdownMutex = new Object();
57          this.status = new AtomicReference<>(IOReactorStatus.INACTIVE);
58          try {
59              this.selector = Selector.open();
60          } catch (final IOException ex) {
61              throw new IllegalStateException("Unexpected failure opening I/O selector", ex);
62          }
63      }
64  
65      @Override
66      public final IOReactorStatus getStatus() {
67          return this.status.get();
68      }
69  
70      void addExceptionEvent(final Throwable ex) {
71          this.auditLog.add(new ExceptionEvent(ex, new Date()));
72      }
73  
74      abstract void doExecute() throws IOException;
75  
76      abstract void doTerminate() throws IOException;
77  
78      public void execute() {
79          if (this.status.compareAndSet(IOReactorStatus.INACTIVE, IOReactorStatus.ACTIVE)) {
80              try {
81                  doExecute();
82              } catch (final ClosedSelectorException ignore) {
83                  // ignore
84              } catch (final Exception ex) {
85                  addExceptionEvent(ex);
86              } finally {
87                  try {
88                      doTerminate();
89                      final Set<SelectionKey> keys = this.selector.keys();
90                      for (final SelectionKey key : keys) {
91                          try {
92                              Closer.close((Closeable) key.attachment());
93                          } catch (final IOException ex) {
94                              addExceptionEvent(ex);
95                          }
96                          key.channel().close();
97                      }
98                      try {
99                          this.selector.close();
100                     } catch (final IOException ex) {
101                         addExceptionEvent(ex);
102                     }
103                 } catch (final Exception ex) {
104                     addExceptionEvent(ex);
105                 } finally {
106                     this.status.set(IOReactorStatus.SHUT_DOWN);
107                     synchronized (this.shutdownMutex) {
108                         this.shutdownMutex.notifyAll();
109                     }
110                 }
111             }
112         }
113     }
114 
115     @Override
116     public final void awaitShutdown(final TimeValue waitTime) throws InterruptedException {
117         Args.notNull(waitTime, "Wait time");
118         final long deadline = System.currentTimeMillis() + waitTime.toMillis();
119         long remaining = waitTime.toMillis();
120         synchronized (this.shutdownMutex) {
121             while (this.status.get().compareTo(IOReactorStatus.SHUT_DOWN) < 0) {
122                 this.shutdownMutex.wait(remaining);
123                 remaining = deadline - System.currentTimeMillis();
124                 if (remaining <= 0) {
125                     return;
126                 }
127             }
128         }
129     }
130 
131     @Override
132     public final void initiateShutdown() {
133         if (this.status.compareAndSet(IOReactorStatus.INACTIVE, IOReactorStatus.SHUT_DOWN)) {
134             synchronized (this.shutdownMutex) {
135                 this.shutdownMutex.notifyAll();
136             }
137         } else if (this.status.compareAndSet(IOReactorStatus.ACTIVE, IOReactorStatus.SHUTTING_DOWN)) {
138             this.selector.wakeup();
139         }
140     }
141 
142     @Override
143     public final void close(final CloseMode closeMode) {
144         if (closeMode == CloseMode.GRACEFUL) {
145             initiateShutdown();
146             try {
147                 awaitShutdown(TimeValue.ofSeconds(5));
148             } catch (final InterruptedException e) {
149                 Thread.currentThread().interrupt();
150             }
151         } else {
152             final IOReactorStatus previousStatus = this.status.getAndSet(IOReactorStatus.SHUT_DOWN);
153             if (previousStatus.compareTo(IOReactorStatus.ACTIVE) == 0) {
154                 this.selector.wakeup();
155             }
156             synchronized (this.shutdownMutex) {
157                 this.shutdownMutex.notifyAll();
158             }
159         }
160     }
161 
162     @Override
163     public final void close() {
164         close(CloseMode.GRACEFUL);
165     }
166 
167     @Override
168     public String toString() {
169         return super.toString() + " [status=" + status + "]";
170     }
171 
172 }