Bump odlparent to 6.0.0
[controller.git] / opendaylight / config / netty-event-executor-config / src / main / java / org / opendaylight / controller / config / yang / netty / eventexecutor / AutoCloseableEventExecutor.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.config.yang.netty.eventexecutor;
9
10 import com.google.common.reflect.AbstractInvocationHandler;
11 import com.google.common.reflect.Reflection;
12 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
13 import io.netty.util.concurrent.EventExecutor;
14 import io.netty.util.concurrent.GlobalEventExecutor;
15 import io.netty.util.concurrent.ImmediateEventExecutor;
16 import java.lang.reflect.Method;
17 import java.util.concurrent.TimeUnit;
18
19 public interface AutoCloseableEventExecutor extends EventExecutor, AutoCloseable {
20
21     static AutoCloseableEventExecutor globalEventExecutor() {
22         return CloseableEventExecutorMixin.createCloseableProxy(GlobalEventExecutor.INSTANCE);
23     }
24
25     static AutoCloseableEventExecutor immediateEventExecutor() {
26         return CloseableEventExecutorMixin.createCloseableProxy(ImmediateEventExecutor.INSTANCE);
27     }
28
29     class CloseableEventExecutorMixin implements AutoCloseable {
30         public static final int DEFAULT_SHUTDOWN_SECONDS = 1;
31         private final EventExecutor eventExecutor;
32
33         public CloseableEventExecutorMixin(final EventExecutor eventExecutor) {
34             this.eventExecutor = eventExecutor;
35         }
36
37         @Override
38         @SuppressFBWarnings(value = "UC_USELESS_VOID_METHOD", justification = "False positive")
39         public void close() {
40             eventExecutor.shutdownGracefully(0, DEFAULT_SHUTDOWN_SECONDS, TimeUnit.SECONDS);
41         }
42
43         static AutoCloseableEventExecutor createCloseableProxy(final EventExecutor eventExecutor) {
44             final CloseableEventExecutorMixin closeableEventExecutor = new CloseableEventExecutorMixin(eventExecutor);
45             return Reflection.newProxy(AutoCloseableEventExecutor.class, new AbstractInvocationHandler() {
46                 @Override
47                 protected Object handleInvocation(final Object proxy, final Method method, final Object[] args)
48                         throws Throwable {
49                     if (method.getName().equals("close")) {
50                         closeableEventExecutor.close();
51                         return null;
52                     } else {
53                         return method.invoke(closeableEventExecutor.eventExecutor, args);
54                     }
55                 }
56             });
57         }
58     }
59 }