一个Java的Actor框架:kilim

11-12-11 banq
              

除了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>

消息发生者,向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>

需要使用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>

在"events vs. threads"争论提及两个问题:线程是重量的;其次线程范式隐式的和共享内存锁联系在一起,导致性能陷阱;而Kilim 试图证明线程也可以和状态机一样轻量,甚至提供一个自动的线程stack管理特性(也就没有必要的 "return to the mainloop" 返回主循环的编程习惯).

              

2