view core/src/luan/modules/ThreadLuan.java @ 582:31926755689e

add Thread.synchronized
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 31 Jul 2015 06:20:17 -0600
parents 6cc2f047019b
children cdc70de628b5
line wrap: on
line source

package luan.modules;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import luan.Luan;
import luan.LuanState;
import luan.LuanFunction;
import luan.LuanTable;
import luan.LuanException;
import luan.DeepCloner;


public final class ThreadLuan {
	private static final Executor exec = Executors.newCachedThreadPool();

	public static void fork(LuanState luan,LuanFunction fn,Object... args) {
		DeepCloner cloner = new DeepCloner();
		final LuanState newLuan = (LuanState)cloner.deepClone(luan);
		final LuanFunction newFn = (LuanFunction)cloner.get(fn);
		final Object[] newArgs = cloner.deepClone(args);
		exec.execute(new Runnable(){public void run() {
			try {
				newFn.call(newLuan,newArgs);
			} catch(LuanException e) {
				e.printStackTrace();
			}
		}});
	}

	public static LuanFunction synchronized_(final LuanState luan,final LuanFunction fn) throws LuanException {
		Utils.checkNotNull(luan,fn);
		return new LuanFunction() {
			@Override public Object call(LuanState ingored,Object[] args) throws LuanException {
				synchronized(luan) {
					return fn.call(luan,args);
				}
			}
		};
	}

}