All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.k0zka.finder4j.backtrack.BacktrackService Maven / Gradle / Ivy

There is a newer version: 0.7
Show newest version
package com.github.k0zka.finder4j.backtrack;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 */
public class BacktrackService {
	private static final Logger logger = LoggerFactory
			.getLogger(BacktrackService.class);

	private final class Worker> implements
			Runnable {
		private final X state;
		private final TerminationStrategy terminationStrategy;
		private final SolutionListener listener;
		private final StepFactory factory;

		private Worker(X state, TerminationStrategy terminationStrategy,
				SolutionListener listener, StepFactory factory) {
			this.state = state;
			this.terminationStrategy = terminationStrategy;
			this.listener = listener;
			this.factory = factory;
		}

		public void run() {
			logger.debug("starting backtrack from state {}", state);
			LocalParallelTrack tracker = new LocalParallelTrack(executorService);
			Backtrack.backtrack(state, factory, terminationStrategy, listener,
					tracker);
			tracker.join();
		}
	}

	private final ForkJoinPool executorService;

	public BacktrackService() {
		this(Runtime.getRuntime().availableProcessors());
	}

	public BacktrackService(final int nrOfCpus) {
		this.executorService = new ForkJoinPool(nrOfCpus);
	}

	public > void backtrack(final X state,
			final StepFactory factory,
			final TerminationStrategy terminationStrategy,
			final SolutionListener listener) {
		try {
			final Future future = executorService.submit(new Worker(
					state, terminationStrategy, listener, factory));
			future.get();
			
		} catch (InterruptedException | ExecutionException e) {
			throw new IllegalStateException(e);
		}
	}

	public void stop() {
		executorService.shutdown();
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy