View Javadoc

    1   /*
    2    * Copyright 2012 The Netty Project
    3    *
    4    * The Netty Project licenses this file to you under the Apache License,
    5    * version 2.0 (the "License"); you may not use this file except in compliance
    6    * with the License. You may obtain a copy of the License at:
    7    *
    8    *   http://www.apache.org/licenses/LICENSE-2.0
    9    *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
    12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
    13   * License for the specific language governing permissions and limitations
    14   * under the License.
    15   */
    16  package org.jboss.netty.handler.execution;
    17
    18  import java.util.concurrent.Executor;
    19
    20  import org.jboss.netty.channel.ChannelEvent;
    21  import org.jboss.netty.channel.ChannelHandlerContext;
    22  import org.jboss.netty.util.EstimatableObjectWrapper;
    23
    24  public abstract class ChannelEventRunnable implements Runnable, EstimatableObjectWrapper {
    25
    26      /**
    27       * An <em>internal use only</em> thread-local variable that tells the
    28       * {@link Executor} that this worker acquired a worker thread from.
    29       */
    30      protected static final ThreadLocal<Executor> PARENT = new ThreadLocal<Executor>();
    31
    32      protected final ChannelHandlerContext ctx;
    33      protected final ChannelEvent e;
    34      int estimatedSize;
    35      private final Executor executor;
    36
    37      /**
    38       * Creates a {@link Runnable} which sends the specified {@link ChannelEvent}
    39       * upstream via the specified {@link ChannelHandlerContext}.
    40       */
    41      public ChannelEventRunnable(ChannelHandlerContext ctx, ChannelEvent e, Executor executor) {
    42          this.ctx = ctx;
    43          this.e = e;
    44          this.executor = executor;
    45      }
    46
    47      /**
    48       * Returns the {@link ChannelHandlerContext} which will be used to
    49       * send the {@link ChannelEvent} upstream.
    50       */
    51      public ChannelHandlerContext getContext() {
    52          return ctx;
    53      }
    54
    55      /**
    56       * Returns the {@link ChannelEvent} which will be sent upstream.
    57       */
    58      public ChannelEvent getEvent() {
    59          return e;
    60      }
    61
    62      public Object unwrap() {
    63          return e;
    64      }
    65
    66      public final void run() {
    67          try {
    68              PARENT.set(executor);
    69              doRun();
    70          } finally {
    71              PARENT.remove();
    72          }
    73
    74      }
    75
    76      protected abstract void doRun();
    77  }