Java的Actor框架--kilim

除了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);
  }
 }
}


消息发生者,向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());
   }
  }
 }
}


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


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值