io.dyn.core.NonBlockingTaskExecutor.java Source code

Java tutorial

Introduction

Here is the source code for io.dyn.core.NonBlockingTaskExecutor.java

Source

/*
 * Copyright (c) 2011-2012 by the original author or authors.
 *
 * 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 io.dyn.core;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

import org.springframework.core.task.TaskExecutor;

/**
 * @author Jon Brisbin <jon@jbrisbin.com>
 */
public class NonBlockingTaskExecutor implements Executor, TaskExecutor {

    private AtomicBoolean active = new AtomicBoolean(true);
    private Executor executor;

    public NonBlockingTaskExecutor() {
        this("executor");
    }

    public NonBlockingTaskExecutor(String name) {
        this(name, 1);
    }

    public NonBlockingTaskExecutor(String name, int internalPoolSize) {
        executor = Executors.newFixedThreadPool(internalPoolSize, Tasks.newThreadFactory(name));
    }

    public boolean active() {
        return active.get();
    }

    public NonBlockingTaskExecutor active(boolean b) {
        active.set(b);
        return this;
    }

    public boolean maybeExecute(Runnable task) {
        if (!active.get()) {
            return false;
        } else {
            execute(task);
            return true;
        }
    }

    @Override
    public void execute(Runnable task) {
        executor.execute(task);
    }

    @Override
    public String toString() {
        return "NonBlockingTaskExecutor{" + ", active=" + active + ", executor=" + executor + '}';
    }
}