/WebBBSC/src/webbbsc/NativeWorker.java
Java | 90 lines | 60 code | 16 blank | 14 comment | 10 complexity | e7095c5740071a8a26bd68c97ad9f736 MD5 | raw file
1package webbbsc;
2
3/**
4 * @author Victor
5 * Interface to a native (written in c++, multithreaded) toolkit for calculating Black Jack base strategies
6 */
7public class NativeWorker extends Thread{
8//public:
9 /**
10 * @param acc: the object to receive strategy in serialized form on calculation finish
11 */
12 public void attachStrategyAcceptor(IRawStrategyAcceptor acc){
13 acceptor = acc;
14 }
15
16 @Override
17 public void run(){
18 if(progress != null)
19 progress.setProgress(0f);
20 if(!prepareCalculation())
21 return;
22
23 //buildNextPiece() is by far the most CPU time consuming here
24 while(!stopped && buildNextPiece()){
25 if(!stopped){
26 float currentProgress = getProgress();
27 if(currentProgress >= 1.0f && acceptor != null)
28 acceptor.acceptStrategy(getRawStrategy());
29 if(progress != null)
30 progress.setProgress(currentProgress);
31 }
32 }
33 }
34
35 public void setRules(Rules newRules){
36 rules = newRules;
37 }
38
39 public void inhibit(boolean stop){
40 stopped = stop;
41 }
42
43 public void terminate(){
44 inhibit(true);
45 while(isAlive()){
46 try{
47 join(1000);
48 }catch(InterruptedException e){
49 }
50 interrupt();
51 }
52 releaseCalculator();
53 }
54
55 /**
56 * @param progr: interface for calling back progress changes
57 */
58 public void attachProgress(IProgressable progr){
59 progress = progr;
60 }
61
62//private:
63 private native void createCalculator();
64 private native void releaseCalculator();
65
66 private Rules rules = new Rules();
67
68 private long calculatorHandle = 0;
69
70 private volatile boolean stopped = false;
71 private IProgressable progress;
72 private IRawStrategyAcceptor acceptor;
73
74 private native boolean buildNextPiece();
75 private native boolean prepareCalculation();
76
77 //progress value is between 0 and 1
78 private native float getProgress();
79
80 private native byte[] getRawStrategy();
81
82
83 static {
84 try {
85 System.loadLibrary("BJEngine");
86 } catch (UnsatisfiedLinkError e) {
87 System.err.println("Native code library failed to load: " + e);
88 }
89 }
90}