/WebBBSC/src/webbbsc/NativeWorker.java

https://bitbucket.org/mild1/bj · Java · 90 lines · 60 code · 16 blank · 14 comment · 10 complexity · e7095c5740071a8a26bd68c97ad9f736 MD5 · raw file

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