hudson.remoting.SynchronousExecutorService Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hudson-remoting Show documentation
Show all versions of hudson-remoting Show documentation
Contains the bootstrap code to bridge separate JVMs into a single semi-shared space.
Reusable outside Hudson.
/*******************************************************************************
*
* Copyright (c) 2004-2010 Oracle Corporation.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*
*
*******************************************************************************/
package hudson.remoting;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
/**
* {@link ExecutorService} that executes synchronously.
*
* @author Kohsuke Kawaguchi
*/
class SynchronousExecutorService extends AbstractExecutorService {
private volatile boolean shutdown = false;
private int count = 0;
public void shutdown() {
shutdown = true;
}
public List shutdownNow() {
shutdown = true;
return Collections.emptyList();
}
public boolean isShutdown() {
return shutdown;
}
public synchronized boolean isTerminated() {
return shutdown && count==0;
}
public synchronized boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
long end = System.currentTimeMillis() + unit.toMillis(timeout);
while (count!=0) {
long d = end - System.currentTimeMillis();
if (d<0) return false;
wait(d);
}
return true;
}
public void execute(Runnable command) {
if (shutdown)
throw new IllegalStateException("Already shut down");
touchCount(1);
try {
command.run();
} finally {
touchCount(-1);
}
}
private synchronized void touchCount(int diff) {
count += diff;
if (count==0)
notifyAll();
}
}