comparison core/src/luan/modules/ThreadLuan.java @ 171:3dcb0f9bee82

add core component git-svn-id: https://luan-java.googlecode.com/svn/trunk@172 21e917c8-12df-6dd8-5cb6-c86387c605b9
author fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9>
date Sun, 22 Jun 2014 05:41:22 +0000
parents src/luan/modules/ThreadLuan.java@ebe9db183eb7
children ec016471c6eb
comparison
equal deleted inserted replaced
170:7c792a328a83 171:3dcb0f9bee82
1 package luan.modules;
2
3 import java.util.concurrent.Executor;
4 import java.util.concurrent.Executors;
5 import luan.LuanState;
6 import luan.LuanFunction;
7 import luan.LuanTable;
8 import luan.LuanJavaFunction;
9 import luan.LuanException;
10 import luan.DeepCloner;
11
12
13 public final class ThreadLuan {
14
15 public static final LuanFunction LOADER = new LuanFunction() {
16 @Override public Object call(LuanState luan,Object[] args) {
17 LuanTable module = new LuanTable();
18 try {
19 add( module, "fork", LuanState.class, LuanFunction.class, new Object[0].getClass() );
20 } catch(NoSuchMethodException e) {
21 throw new RuntimeException(e);
22 }
23 return module;
24 }
25 };
26
27 private static void add(LuanTable t,String method,Class<?>... parameterTypes) throws NoSuchMethodException {
28 t.put( method, new LuanJavaFunction(ThreadLuan.class.getMethod(method,parameterTypes),null) );
29 }
30
31 private static final Executor exec = Executors.newCachedThreadPool();
32
33 public static void fork(LuanState luan,LuanFunction fn,Object... args) {
34 DeepCloner cloner = new DeepCloner();
35 final LuanState newLuan = cloner.deepClone(luan);
36 final LuanFunction newFn = cloner.get(fn);
37 final Object[] newArgs = cloner.deepClone(args);
38 exec.execute(new Runnable(){public void run() {
39 try {
40 newLuan.call(newFn,"<forked>",newArgs);
41 } catch(LuanException e) {
42 e.printStackTrace();
43 }
44 }});
45 }
46
47 }