一個Java的Actor框架:kilim

banq發表於2011-12-11
除了Akka以外,另外一個將類似Erlang和Scala的Actor的併發模型引入Java的開源框架:kilim/kilim - GitHub,其使用了一種mailbox跨執行緒共享記憶體,沒有鎖或同步。

訊息消費者程式碼如下,監聽mailbox:

public class Calculator extends Task{
 
 private Mailbox<calculation> mailbox;
 
 public Calculator(Mailbox<calculation> mailbox) {
  super();
  this.mailbox = mailbox;
 }
 
 @[author]Override[/author]
 public void execute() throws Pausable, Exception {
  while (true) {   
   Calculation calc = mailbox.get(); // blocks
   if (calc.getAnswer() == null) {
    calc.setAnswer(calc.getDividend().divide(calc.getDivisor(), 8, 
      RoundingMode.HALF_UP));    
    System.out.println("Calculator determined answer");
    mailbox.putnb(calc);
   }
   Task.sleep(1000);
  }
 }
}
<p class="indent">


訊息發生者,向mailbox傳送訊息:

public class DeferredDivision extends Task {
 
 private Mailbox<calculation> mailbox;
 
 public DeferredDivision(Mailbox<calculation> mailbox) {
  super();
  this.mailbox = mailbox;
 }
 
 @[author]Override[/author]
 public void execute() throws Pausable, Exception {
  Random numberGenerator = new Random(new Date().getTime());
  MathContext context = new MathContext(8);
  while (true) {
   System.out.println("I need to know the answer of something");
   mailbox.putnb(new Calculation(
     new BigDecimal(numberGenerator.nextDouble(), context), 
     new BigDecimal(numberGenerator.nextDouble(), context)));
   Task.sleep(1000);
   Calculation answer = mailbox.getnb(); // no block
   if (answer != null && answer.getAnswer() != null) {
    System.out.println("Answer is: " + answer.printAnswer());
   }
  }
 }
}
<p class="indent">


需要使用Ant呼叫 Kilim's weaver(byte code enhancer):
<target name="weave" depends="compile" description="handles Kilim byte code weaving">
<java classname="kilim.tools.Weaver" fork="yes">
<classpath refid="classpath">
<arg value="-d">
<arg value="./target/classes">
<arg line="./target/classes">
</arg></arg></arg></classpath></java>
</target>

客戶端測試程式碼:

 Mailbox<calculation> sharedMailbox = new Mailbox<calculation>();
 
  Task deferred = new DeferredDivision(sharedMailbox);
  Task calculator = new Calculator(sharedMailbox);
 
  deffered.start();
  calculator.start();
<p class="indent">


在"events vs. threads"爭論提及兩個問題:執行緒是重量的;其次執行緒正規化隱式的和共享記憶體鎖聯絡在一起,導致效能陷阱;而Kilim 試圖證明執行緒也可以和狀態機一樣輕量,甚至提供一個自動的執行緒stack管理特性(也就沒有必要的 "return to the mainloop" 返回主迴圈的程式設計習慣).

相關文章