com.metamx.common.guava.ExecutorExecutingSequence Maven / Gradle / Ivy
/*
* Copyright 2011,2012 Metamarkets Group Inc.
*
* 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.metamx.common.guava;
import com.google.common.base.Throwables;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
/**
*/
public class ExecutorExecutingSequence implements Sequence
{
private final Sequence sequence;
private final ExecutorService exec;
public ExecutorExecutingSequence(
Sequence sequence,
ExecutorService exec
)
{
this.sequence = sequence;
this.exec = exec;
}
@Override
public OutType accumulate(final OutType initValue, final Accumulator accumulator)
{
Future future = exec.submit(
new Callable()
{
@Override
public OutType call() throws Exception
{
return sequence.accumulate(initValue, accumulator);
}
}
);
try {
return future.get();
}
catch (InterruptedException e) {
throw Throwables.propagate(e);
}
catch (ExecutionException e) {
throw Throwables.propagate(e);
}
}
@Override
public Yielder toYielder(final OutType initValue, final YieldingAccumulator accumulator)
{
Future> future = exec.submit(
new Callable>()
{
@Override
public Yielder call() throws Exception
{
return makeYielder(sequence.toYielder(initValue, accumulator));
}
}
);
try {
return future.get();
}
catch (InterruptedException e) {
throw Throwables.propagate(e);
}
catch (ExecutionException e) {
throw Throwables.propagate(e);
}
}
private Yielder makeYielder(final Yielder yielder)
{
return new Yielder()
{
@Override
public OutType get()
{
return yielder.get();
}
@Override
public Yielder next(final OutType initValue)
{
Future> future = exec.submit(
new Callable>()
{
@Override
public Yielder call() throws Exception
{
return makeYielder(yielder.next(initValue));
}
}
);
try {
return future.get();
}
catch (InterruptedException e) {
throw Throwables.propagate(e);
}
catch (ExecutionException e) {
throw Throwables.propagate(e);
}
}
@Override
public boolean isDone()
{
return yielder.isDone();
}
@Override
public void close() throws IOException
{
yielder.close();
}
};
}
}