Posted By

sai-venkat on 02/16/10


Tagged

message jruby passing concurrency jetlang


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

sai-venkat


JRuby Jetlang Pingpong Example


 / Published in: Ruby
 

  1. require "java"
  2. require "jetlang-0.2.0.jar"
  3.  
  4. include_class "org.jetlang.fibers.ThreadFiber"
  5. include_class "org.jetlang.channels.MemoryChannel"
  6. include_class "org.jetlang.channels.BatchSubscriber"
  7. include_class "java.util.concurrent.CountDownLatch"
  8. include_class "java.util.concurrent.TimeUnit"
  9.  
  10. class PingPongChannels
  11. def ping
  12. return @ping_channel ||= MemoryChannel.new
  13. end
  14. def pong
  15. return @pong_channel ||= MemoryChannel.new
  16. end
  17. def stop
  18. return @stop_channel ||= MemoryChannel.new
  19. end
  20. end
  21.  
  22. class Ping
  23. def initialize(channels, fiber, count)
  24. @channels = channels
  25. @consumer = fiber
  26. @count = count
  27. end
  28. def start
  29. on_receive = Proc.new do |message|
  30. if @count > 0
  31. publish_ping(message)
  32. else
  33. @channels.stop.publish("")
  34. @consumer.dispose
  35. end
  36. end
  37. @channels.ping.subscribe(@consumer, on_receive)
  38.  
  39. @consumer.start
  40. end
  41. def publish_ping(message)
  42. puts message
  43. @count -= 1
  44. @channels.pong.publish("From ping to pong")
  45. end
  46. end
  47.  
  48. class Pong
  49. def initialize(channels, fiber)
  50. @channels = channels
  51. @consumer = fiber
  52. end
  53. def start
  54. on_receive = Proc.new do |message|
  55. puts message
  56. @channels.ping.publish("From pong to ping")
  57. end
  58. @channels.pong.subscribe(@consumer, on_receive)
  59. on_stop = Proc.new {|message| @consumer.dispose}
  60. @channels.stop.subscribe(@consumer, on_stop)
  61. @consumer.start
  62. end
  63. end
  64.  
  65. channels = PingPongChannels.new
  66. ping_thread = ThreadFiber.new
  67. pong_thread = ThreadFiber.new
  68.  
  69. ping = Ping.new(channels, ping_thread, 1000)
  70. pong = Pong.new(channels, pong_thread)
  71.  
  72. pong.start
  73. ping.start
  74.  
  75. channels.ping.publish("Start Game")
  76.  
  77. ping_thread.join
  78. pong_thread.join

Report this snippet  

You need to login to post a comment.