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

astra.execution.AdaptiveSchedulerStrategy Maven / Gradle / Ivy

There is a newer version: 1.4.2
Show newest version
package astra.execution;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import astra.core.Agent;
import astra.core.Scheduler;
import astra.core.Task;

public class AdaptiveSchedulerStrategy implements SchedulerStrategy {
	private ExecutorService executor = Executors.newFixedThreadPool(5);
	private Map agents = new HashMap();
	
	public void schedule(final Agent agent) {
		Integer state = null;
		// synchronized (this) {
			state = agents.get(agent.name());
			if (state == null) {
				agents.put(agent.name(), state = Scheduler.ACTIVE);
			// }
		}
		
		if (state == Scheduler.ACTIVE) {
			executor.submit(new Runnable() {
				public void run() {
					try {
						agent.execute();
					} catch (Throwable th) {
						System.err.println("Major Error in Agent: " + agent.name());
						th.printStackTrace();
						System.exit(0);
					}
					
					synchronized (agent) {
						if ((agent.hasSensors()) || !(agent.hasEvents() && agent.intentions().isEmpty()) || agent.hasActiveFunction()) {
							schedule(agent);
						} else {
							agents.put(agent.name(), Scheduler.WAITING);
							System.out.println("SUSPENDING: " + agent.name());
							System.out.println("["+agent.name()+"] events: " + agent.events());
							System.out.println("["+agent.name()+"] intentions: " + agent.intentions());
						}
					}
				}
			});
		}
	}

	public void schedule(Task task) {
		executor.submit(task);
	}

	public void setThreadPoolSize(int size) {
		ExecutorService oldExecutor = executor;
		executor = Executors.newFixedThreadPool(size);
		oldExecutor.shutdown();
	}

	public void stop() {
	}

	public void setState(Agent agent, int state) {
		agents.put(agent.name(), state);
	}

	public synchronized int getState(Agent agent) {
		if (!agents.containsKey(agent.name())) return Scheduler.ACTIVE;
		return agents.get(agent.name());
	}

	public void setSleepTime(long sleepTime) {
	}

	public void shutdown() {
		executor.shutdownNow();
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy