I am trying to solve VRPs with OptaPlanner. I wrote all the code with constraint provider, planning entities and planning solution etc. The question is, I am trying to fetch the solution by
SolverConfig solverConfig = new SolverConfig();
solverConfig.withSolutionClass(Solution.class);
solverConfig.withEntityClasses(Stop.class, Standstill.class);
ScoreDirectorFactoryConfig scoreDirectorFactoryConfig = new ScoreDirectorFactoryConfig();
scoreDirectorFactoryConfig.setConstraintProviderClass(VrpConstraintProvider.class);
solverConfig.withScoreDirectorFactory(scoreDirectorFactoryConfig);
SolverFactory<Solution> solverFactory = SolverFactory.create(solverConfig);
Solver<Solution> solver = solverFactory.buildSolver();
Solution solution = solver.solve(solutionDef);
but this causes an endless waiting for solution. Are there any ideas of what is the reason? Thanks in advance.
You haven't configured the solver termination condition. For example, if you want the solver to solve for 60 seconds, add this:
solverConfig.withTerminationConfig(new TerminationConfig().withSecondsSpentLimit(60L));
Note that in the example you present solver runs on the main thread and blocks it until the termination condition is met and it stops solving voluntarily. Since there is no such condition in your example, it solves and blocks the thread forever.
Alternatively, use the SolverManager
API to solve a problem asynchronously (on a worker thread):
int problemId = 1;
SolverManager<Solution, Integer> solverManager = SolverManager.create(
solverConfig, new SolverManagerConfig());
SolverJob<Solution, Integer> solverJob = solverManager.solve(problemId, solutionDef);
// wait some time, then terminate solver manager
solverManager.terminateEarly(problemId);
Solution bestSolution = solverJob.getFinalBestSolution();