001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019 package org.apache.hadoop.lib.lang;
020
021 import org.apache.hadoop.classification.InterfaceAudience;
022 import org.apache.hadoop.lib.util.Check;
023
024 import java.util.concurrent.Callable;
025
026 /**
027 * Adapter class that allows <code>Runnable</code>s and <code>Callable</code>s to
028 * be treated as the other.
029 */
030 @InterfaceAudience.Private
031 public class RunnableCallable implements Callable<Void>, Runnable {
032 private Runnable runnable;
033 private Callable<?> callable;
034
035 /**
036 * Constructor that takes a runnable.
037 *
038 * @param runnable runnable.
039 */
040 public RunnableCallable(Runnable runnable) {
041 this.runnable = Check.notNull(runnable, "runnable");
042 }
043
044 /**
045 * Constructor that takes a callable.
046 *
047 * @param callable callable.
048 */
049 public RunnableCallable(Callable<?> callable) {
050 this.callable = Check.notNull(callable, "callable");
051 }
052
053 /**
054 * Invokes the wrapped callable/runnable as a callable.
055 *
056 * @return void
057 *
058 * @throws Exception thrown by the wrapped callable/runnable invocation.
059 */
060 @Override
061 public Void call() throws Exception {
062 if (runnable != null) {
063 runnable.run();
064 } else {
065 callable.call();
066 }
067 return null;
068 }
069
070 /**
071 * Invokes the wrapped callable/runnable as a runnable.
072 *
073 * @throws RuntimeException thrown by the wrapped callable/runnable invocation.
074 */
075 @Override
076 public void run() {
077 if (runnable != null) {
078 runnable.run();
079 } else {
080 try {
081 callable.call();
082 } catch (Exception ex) {
083 throw new RuntimeException(ex);
084 }
085 }
086 }
087
088 /**
089 * Returns the class name of the wrapper callable/runnable.
090 *
091 * @return the class name of the wrapper callable/runnable.
092 */
093 @Override
094 public String toString() {
095 return (runnable != null) ? runnable.getClass().getSimpleName() : callable.getClass().getSimpleName();
096 }
097 }