package org.kne.acclerate;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import org.kne.io.Task;

public class FastLib {
	private static int cores=Runtime.getRuntime().availableProcessors();
	private static ExecutorService exc=Executors.newFixedThreadPool(cores,new ThreadFactory() {
		
		@Override
		public Thread newThread(Runnable r) {
			Thread t=new Thread(r);
			t.setDaemon(true);
			t.setPriority(Thread.MAX_PRIORITY);
			return t;
		}
	});
	public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) {
		if(length<2000) {
		System.arraycopy(src, srcPos, dest, destPos, length);
		}else {
			int count=length/cores;
			int mod=length%cores;
			Task[]tsk=new Task[cores];
			for (int i = 0; i < cores; i++) {
				int j=i;
				Task t=new Task() {
					
					@Override
					protected void runTask() {
						System.arraycopy(src, srcPos+count*j, dest, destPos+count*j, count);
					}
				};
				exc.execute(t);
				tsk[i]=t;
			}
			System.arraycopy(src, srcPos+count*cores, dest, destPos+count*cores, mod);
			for (int i = 0; i < tsk.length; i++) {
				tsk[i].waitfortask();
			}
		}
	}
}
