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.util.Args;
42  import org.apache.hc.core5.util.TimeValue;
43  
44  abstract class AbstractSingleCoreIOReactor implements IOReactor {
45  
46      private final Queue<ExceptionEvent> auditLog;
47      private final AtomicReference<IOReactorStatus> status;
48      private final Object shutdownMutex;
49  
50      final Selector selector;
51  
52      AbstractSingleCoreIOReactor(final Queue<ExceptionEvent> auditLog) {
53          super();
54          this.auditLog = auditLog;
55          this.shutdownMutex = new Object();
56          this.status = new AtomicReference<>(IOReactorStatus.INACTIVE);
57          try {
58              this.selector = Selector.open();
59          } catch (final IOException ex) {
60              throw new IllegalStateException("Unexpected failure opening I/O selector", ex);
61          }
62      }
63  
64      @Override
65      public final IOReactorStatus getStatus() {
66          return this.status.get();
67      }
68  
69      void addExceptionEvent(final Throwable ex) {
70          this.auditLog.add(new ExceptionEvent(ex, new Date()));
71      }
72  
73      abstract void doExecute() throws IOException;
74  
75      abstract void doTerminate() throws IOException;
76  
77      public void execute() {
78          if (this.status.compareAndSet(IOReactorStatus.INACTIVE, IOReactorStatus.ACTIVE)) {
79              try {
80                  doExecute();
81              } catch (final ClosedSelectorException ignore) {
82              } catch (final Exception ex) {
83                  addExceptionEvent(ex);
84              } finally {
85                  try {
86                      doTerminate();
87                      final Set<SelectionKey> keys = this.selector.keys();
88                      for (final SelectionKey key : keys) {
89                          final Closeable closeable = (Closeable) key.attachment();
90                          if (closeable != null) {
91                              try {
92                                  closeable.close();
93                              } catch (final IOException ex) {
94                                  addExceptionEvent(ex);
95                              }
96                          }
97                          key.channel().close();
98                      }
99                      try {
100                         this.selector.close();
101                     } catch (final IOException ex) {
102                         addExceptionEvent(ex);
103                     }
104                 } catch (final Exception ex) {
105                     addExceptionEvent(ex);
106                 } finally {
107                     this.status.set(IOReactorStatus.SHUT_DOWN);
108                     synchronized (this.shutdownMutex) {
109                         this.shutdownMutex.notifyAll();
110                     }
111                 }
112             }
113         }
114     }
115 
116     @Override
117     public final void awaitShutdown(final TimeValue waitTime) throws InterruptedException {
118         Args.notNull(waitTime, "Wait time");
119         final long deadline = System.currentTimeMillis() + waitTime.toMillis();
120         long remaining = waitTime.toMillis();
121         synchronized (this.shutdownMutex) {
122             while (this.status.get().compareTo(IOReactorStatus.SHUT_DOWN) < 0) {
123                 this.shutdownMutex.wait(remaining);
124                 remaining = deadline - System.currentTimeMillis();
125                 if (remaining <= 0) {
126                     return;
127                 }
128             }
129         }
130     }
131 
132     @Override
133     public final void initiateShutdown() {
134         if (this.status.compareAndSet(IOReactorStatus.INACTIVE, IOReactorStatus.SHUT_DOWN)) {
135             synchronized (this.shutdownMutex) {
136                 this.shutdownMutex.notifyAll();
137             }
138         } else if (this.status.compareAndSet(IOReactorStatus.ACTIVE, IOReactorStatus.SHUTTING_DOWN)) {
139             this.selector.wakeup();
140         }
141     }
142 
143     @Override
144     public final void close(final CloseMode closeMode) {
145         if (closeMode == CloseMode.GRACEFUL) {
146             initiateShutdown();
147             try {
148                 awaitShutdown(TimeValue.ofSeconds(5));
149             } catch (final InterruptedException e) {
150                 Thread.currentThread().interrupt();
151             }
152         } else {
153             final IOReactorStatus previousStatus = this.status.getAndSet(IOReactorStatus.SHUT_DOWN);
154             if (previousStatus.compareTo(IOReactorStatus.ACTIVE) == 0) {
155                 this.selector.wakeup();
156             }
157             synchronized (this.shutdownMutex) {
158                 this.shutdownMutex.notifyAll();
159             }
160         }
161     }
162 
163     @Override
164     public final void close() {
165         close(CloseMode.GRACEFUL);
166     }
167 
168     @Override
169     public String toString() {
170         return super.toString() + " [status=" + status + "]";
171     }
172 
173 }