Skip to content

Instantly share code, notes, and snippets.

@anildigital

anildigital/JRuby.md

Last active Oct 7, 2017
Embed
What would you like to do?
PuneRb - JRuby talk - Saturday, October 7th, 2017
require 'java'
java_import 'javax.swing.JFrame'
java_import 'javax.swing.JPanel'
java_import 'java.awt.Dimension'
class MyPanel < JPanel
def paintComponent(graphics)
1000.times do |i|
x = Math.sin(i) + 1
y = Math.cos(i * 0.2) + 1
graphics.draw_oval(x * 320, y * 240, 10, 10)
end
end
end
frame = JFrame.new 'Hello, JRuby!'
frame.size = Dimension.new 640, 480
panel = MyPanel.new
frame.add panel
frame.visible = true
require "java"
java_import javax.swing.JFrame
java_import javax.swing.JButton
java_import javax.swing.JOptionPane
class HelloWorld < JFrame
def initialize
super "Example"
setSize(150, 100)
setDefaultCloseOperation(JFrame::EXIT_ON_CLOSE)
setLocationRelativeTo(nil)
button = JButton.new("Say Hello")
add(button)
button.addActionListener do |e|
JOptionPane.showMessageDialog(nil, "Hello World")
end
setVisible(true)
end
end
HelloWorld.new
javax.swing.JOptionPane.showMessageDialog(nil, "Hello World!")
require 'benchmark'
def task
tmp_array = []
10_000_000.times { |n| tmp_array << n }
end
task_method = method(:task)
@threads = []
Benchmark.bm(14) do |x|
x.report('no-threads') do
2.times do
task
end
end
x.report('with-threads') do
2.times do
@threads << Thread.new(&task_method)
end
@threads.each(&:join)
end
end
require 'open-uri'
require 'benchmark'
URL = 'http://google.com'
TIMES = 15.times
puts "RUBY_PLATFORM #{RUBY_PLATFORM}"
puts "RUBY_VERSION #{RUBY_VERSION}\n\n"
def without_threads
TIMES.map { open(URL) }
end
def with_threads
TIMES.map do
Thread.new { open(URL) }
end.each(&:join)
end
Benchmark.bm do |x|
x.report("Without threads\n") {
without_threads
}
x.report("With threads\n") {
with_threads
}
end
@anildigital

This comment has been minimized.

Copy link
Owner Author

@anildigital anildigital commented Oct 7, 2017

You can compile JRuby programs with jrubyc command as below

jrubyc thread_cpu_bound.rb

Then you can execute program as (P.S. jruby-complete.jar can be used to run jruby compiled classes with Java)

java -cp ~/Downloads/jruby-complete-9.1.13.0.jar org.jruby.Main -S thread_cpu_bound.class

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment