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

convex.peer.CVMExecutor Maven / Gradle / Ivy

The newest version!
package convex.peer;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

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

import convex.core.Belief;
import convex.core.Peer;
import convex.core.util.LatestUpdateQueue;
import convex.core.util.LoadMonitor;

/**
 * Component handling CVM execution loop with a Peer Server
 */
public class CVMExecutor extends AThreadedComponent {
	
	private static final Logger log = LoggerFactory.getLogger(CVMExecutor.class.getName());
	
	private Peer peer;
	
	private Consumer updateHook=null;
	
	private LatestUpdateQueue update=new LatestUpdateQueue<>();

	public CVMExecutor(Server server) {
		super(server);
	}

	@Override
	protected void loop() throws InterruptedException {
		// poll for any Belief change
		LoadMonitor.down();
		Belief beliefUpdate=update.poll(100, TimeUnit.MILLISECONDS);
		LoadMonitor.up();
		
		synchronized(this) {
			if (beliefUpdate!=null) {
				peer=peer.updateBelief(beliefUpdate);
			}
			
			// Trigger State update (if any new Blocks are confirmed)
			Peer updatedPeer=peer.updateState();
			if (updatedPeer!=peer) {
				peer=updatedPeer;
				try {
					persistPeerData();
				} catch (IOException e) {
					log.debug("IO Exception ("+e.getMessage()+") while persisting peer data",e);
					throw new InterruptedException("IO Exception while persisting peer data");
				}
				maybeCallHook(peer);
			}
		}
		
		server.transactionHandler.maybeReportTransactions(peer);
	}
	
	public synchronized void persistPeerData() throws IOException {
		peer = server.persistPeerData();

	}

	private void maybeCallHook(Peer p) {
		Consumer hook=updateHook;
		if (hook==null) return;
		
		hook.accept(p);
	}

	@Override
	protected String getThreadName() {
		return "CVM Executor thread on port "+server.getPort();
	}

	public synchronized void setPeer(Peer peer) {
		this.peer=peer;
	}
	
	public Peer getPeer() {
		return peer;
	}

	public void queueUpdate(Belief belief) {
		update.offer(belief);
	}

	public void setUpdateHook(Consumer hook) {
		updateHook=hook;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy