RotateThread.java example:


/*
* Copyright (c) CoralBlocks LLC (c) 2017
 */
package com.coralblocks.coralthreads.sample;

import java.util.List;

import com.coralblocks.coralbits.util.SystemUtils;
import com.coralblocks.coralthreads.Affinity;
import com.coralblocks.coralthreads.Processor;

public class RotateThread {
	
	public static void main(String[] args) throws Exception {
		
		class MyThread extends Thread {
		
			private volatile boolean running = true;
			private int procToBind = -1;
			
			public MyThread(String name, int procToBind) {
				super(name);
				this.procToBind = procToBind;
			}
			
			public synchronized void changeProcToBind(int newProcToBind) {
				this.procToBind = newProcToBind;
			}
			
			public void stopMe() {
				this.running = false;
			}
			
			@Override
			public void run() {
				
				Affinity.bind();

				int currProcToBind = procToBind;
				
				try {
				
    				while(running) {
    					
    					synchronized(this) {
    					
    						if (currProcToBind != procToBind) {
    							
    							Affinity.unbind();
    							
    							Affinity.assignToProcessor(procToBind, this);
    							
    							currProcToBind = procToBind;
    							
    							Affinity.bind();
    						}
    						
    					}
    				}
    				
				} finally {
					
					Affinity.unbind();
				}
			}
		}
		
		List<Processor> procs = Affinity.getProcessors();
		if (procs.isEmpty()) throw new RuntimeException("No processors were found!");
		int procToBind = procs.get(0).getId();
		
		MyThread t = new MyThread("RotatingThread", procToBind);
		Affinity.assignToProcessor(procToBind, t); // start with the first one...
		t.start();

		System.out.println("Thread started on processor " + procToBind + "...");
		
		int timePerProcInMillis = SystemUtils.getInt("timePerProcInSeconds", 10) * 1000;
		
		for(int i = 1; i < procs.size(); i++) {
			
			Thread.sleep(timePerProcInMillis);
		
			int id = procs.get(i).getId();
			
			System.out.println("Changing thread to processor " + id + "...");
			
			t.changeProcToBind(id);
		}
		
		t.stopMe();
		t.join();
	}
}