com.github.jeluard.guayaba.lang.Runnables.java Source code

Java tutorial

Introduction

Here is the source code for com.github.jeluard.guayaba.lang.Runnables.java

Source

/**
 * Copyright 2012 Julien Eluard
 * This project includes software developed by Julien Eluard: https://github.com/jeluard/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.jeluard.guayaba.lang;

import com.google.common.base.Preconditions;

import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Helper methods for {@link Runnable}.
 */
public final class Runnables {

    private Runnables() {
    }

    /**
     * @param runnable
     * @param logger
     * @return specified {@link Runnable} in a new {@link Runnable} that will intercept and log any exception thrown by {@link Runnable#run()}
     */
    public static Runnable loggingExecutionFailure(final Runnable runnable, final Logger logger) {
        Preconditions.checkNotNull(runnable, "null runnable");
        Preconditions.checkNotNull(logger, "null logger");

        return new Runnable() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } catch (Exception e) {
                    if (logger.isLoggable(Level.WARNING)) {
                        logger.log(Level.WARNING, "Exception while executing <" + runnable + ">", e);
                    }
                }
            }
        };
    }

    /**
     * @param runnable
     * @return a {@link Callable} encapsulating specified {@link Runnable} logic
     */
    public static Callable<Void> asCallable(final Runnable runnable) {
        Preconditions.checkNotNull(runnable, "null runnable");

        return new Callable<Void>() {
            @Override
            public Void call() {
                runnable.run();
                return null;
            }

            @Override
            public String toString() {
                return runnable.toString();
            }
        };
    }

}