Mercurial Hosting > luan
comparison src/luan/modules/ThreadLuan.java @ 775:1a68fc55a80c
simplify dir structure
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Fri, 26 Aug 2016 14:36:40 -0600 |
parents | core/src/luan/modules/ThreadLuan.java@a82d385ec2c3 |
children | fbbdd369a13a |
comparison
equal
deleted
inserted
replaced
774:3e30cf310e56 | 775:1a68fc55a80c |
---|---|
1 package luan.modules; | |
2 | |
3 import java.io.Closeable; | |
4 import java.util.concurrent.Executor; | |
5 import java.util.concurrent.Executors; | |
6 import java.util.concurrent.ScheduledExecutorService; | |
7 import java.util.concurrent.ScheduledFuture; | |
8 import java.util.concurrent.TimeUnit; | |
9 import luan.Luan; | |
10 import luan.LuanState; | |
11 import luan.LuanFunction; | |
12 import luan.LuanTable; | |
13 import luan.LuanException; | |
14 import luan.DeepCloner; | |
15 | |
16 | |
17 public final class ThreadLuan { | |
18 private static final Executor exec = Executors.newCachedThreadPool(); | |
19 private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); | |
20 | |
21 public static void fork(LuanState luan,LuanFunction fn,Object... args) { | |
22 DeepCloner cloner = new DeepCloner(); | |
23 final LuanState newLuan = (LuanState)cloner.deepClone(luan); | |
24 final LuanFunction newFn = (LuanFunction)cloner.get(fn); | |
25 final Object[] newArgs = cloner.deepClone(args); | |
26 exec.execute(new Runnable(){public void run() { | |
27 try { | |
28 newFn.call(newLuan,newArgs); | |
29 } catch(LuanException e) { | |
30 e.printStackTrace(); | |
31 } | |
32 }}); | |
33 } | |
34 | |
35 public static LuanFunction synchronized_(final LuanState luan,final LuanFunction fn) throws LuanException { | |
36 Utils.checkNotNull(fn); | |
37 return new LuanFunction() { | |
38 @Override public Object call(LuanState ingored,Object[] args) throws LuanException { | |
39 synchronized(luan) { | |
40 return fn.call(luan,args); | |
41 } | |
42 } | |
43 }; | |
44 } | |
45 | |
46 public static void schedule(LuanState luan,long delay,boolean repeat,LuanFunction fn,Object... args) { | |
47 DeepCloner cloner = new DeepCloner(); | |
48 final LuanState newLuan = (LuanState)cloner.deepClone(luan); | |
49 final LuanFunction newFn = (LuanFunction)cloner.get(fn); | |
50 final Object[] newArgs = cloner.deepClone(args); | |
51 Runnable r = new Runnable(){public void run() { | |
52 try { | |
53 newFn.call(newLuan,newArgs); | |
54 } catch(LuanException e) { | |
55 e.printStackTrace(); | |
56 } | |
57 }}; | |
58 final ScheduledFuture sf; | |
59 if( repeat ) { | |
60 sf = scheduler.scheduleWithFixedDelay(r,delay,delay,TimeUnit.MILLISECONDS); | |
61 } else { | |
62 sf = scheduler.schedule(r,delay,TimeUnit.MILLISECONDS); | |
63 } | |
64 final Closeable c = new Closeable(){public void close(){ | |
65 boolean b = sf.cancel(false); | |
66 }}; | |
67 luan.registry().put(c,c); // prevent gc | |
68 luan.onClose(c); | |
69 } | |
70 | |
71 } |