SlideShare uma empresa Scribd logo
1 de 43
Extending JRuby
JRubyConf 2010
Jeremy Hinegardner
All Work

Collective Intellect
All Play

github.com/copiousfreetime
Dull Boy
@copiousfreetime
Extensions
Ruby
Program
Ruby
Program




          Some
          Awesome
          Library
           sal.{dll,so,jar}
Ruby
Program


          Ruby
          Runtime



                    Some
                    Awesome
                    Library
                     sal.{dll,so,jar}
Ruby
Program


          Ruby
          Runtime


                    Extension
                       API      Some
                                Awesome
                                Library
                                 sal.{dll,so,jar}
Ruby
Program


          Ruby
          Runtime


                    Extension
                                Extension
                       API                  Some
                                            Awesome
                                            Library
                                             sal.{dll,so,jar}
Hitimes
MRI - C Extensions
How Many of You Have ...




    ... A C Extension
How Many of You Have ...
          USED




    ... A C Extension
How Many of You Have ...
             USED

  LOOKED AT THE SOURCE CODE OF




     ... A C Extension
How Many of You Have ...
             USED

  LOOKED AT THE SOURCE CODE OF

            WRITTEN


     ... A C Extension
C Extension Trace
C Extension Trace
% irb
>> require 'rubygems'
>> require 'hitimes'
C Extension Trace
% irb
>> require 'rubygems'| grep require
 % cat lib/hitimes.rb
 require 'hitimes/paths'
>> require 'hitimes'
 require 'hitimes/version'
 require "hitimes/#{RUBY_VERSION.sub(/.d$/,'')}/hitimes_ext"
 ...
C Extension Trace
% irb
>> require 'rubygems'| grep require
 % cat lib/hitimes.rb
 require 'hitimes/paths'
>> require 'hitimes'
 require 'hitimes/version'
 require "hitimes/#{RUBY_VERSION.sub(/.d$/,'')}/hitimes_ext"
     % find ./lib -type f -name 'hitimes_ext*'
 ... ./lib/hitimes/1.8/hitimes_ext.bundle
     ...
C Extension Trace
% irb
>> require 'rubygems'| grep require
 % cat lib/hitimes.rb
 require 'hitimes/paths'
>> require 'hitimes'
 require 'hitimes/version'
 require "hitimes/#{RUBY_VERSION.sub(/.d$/,'')}/hitimes_ext"
     % find ./lib -type f -name 'hitimes_ext*'
 ... ./lib/hitimes/1.8/hitimes_ext.bundle
     ...
             % cat ext/hitimes/hitimes_ext.c
             void Init_hitimes_ext( )
             {
                mH = rb_define_module("Hitimes");

              eH_Error = rb_define_class_under(mH, "Error", rb_eStandardError);

              Init_hitimes_interval();
              Init_hitimes_stats( );
          }
void Init_hitimes_interval()
{
  mH = rb_define_module("Hitimes");

    cH_Interval = rb_define_class_under( mH, "Interval", rb_cObject );
    rb_define_alloc_func( cH_Interval, hitimes_interval_alloc );

    rb_define_module_function( cH_Interval, "now", hitimes_interval_now, 0 );
    rb_define_module_function( cH_Interval, "measure", hitimes_interval_measure, 0 );

    rb_define_method( cH_Interval, "duration",     hitimes_interval_duration, 0 );

    rb_define_method( cH_Interval, "duration_so_far", hitimes_interval_duration_so_far, 0);
    rb_define_method( cH_Interval, "started?", hitimes_interval_started, 0 );
    rb_define_method( cH_Interval, "running?", hitimes_interval_running, 0 );
    rb_define_method( cH_Interval, "stopped?", hitimes_interval_stopped, 0 );

    rb_define_method( cH_Interval, "start_instant", hitimes_interval_start_instant, 0 );
    rb_define_method( cH_Interval, "stop_instant", hitimes_interval_stop_instant, 0 );

    rb_define_method( cH_Interval, "start", hitimes_interval_start, 0);
    rb_define_method( cH_Interval, "stop", hitimes_interval_stop, 0);
    rb_define_method( cH_Interval, "split", hitimes_interval_split, 0);
}
JRuby - Java Extensions
_WHY?
_Why Not?
Hitimes
hitimes_instant_t hitimes_get_current_instant() {
   LARGE_INTEGER tick;
   QueryPerformanceCounter(&tick);
   return (hitimes_instant_t)tick.QuadPart;
}
hitimes_instant_t hitimes_get_current_instant() {
   LARGE_INTEGER tick;
   QueryPerformanceCounter(&tick);
   return (hitimes_instant_t)tick.QuadPart;
}




          hitimes_instant_t hitimes_get_current_instant( ) {
             Nanoseconds nano =
                AbsoluteToNanoseconds( UpTime() );
             return *( hitimes_instant_t *)&nano;
          }
hitimes_instant_t hitimes_get_current_instant() {
   LARGE_INTEGER tick;
   QueryPerformanceCounter(&tick);
   return (hitimes_instant_t)tick.QuadPart;
}




          hitimes_instant_t hitimes_get_current_instant( ) {
             Nanoseconds nano =
                AbsoluteToNanoseconds( UpTime() );
             return *( hitimes_instant_t *)&nano;
          }




                        hitimes_instant_t hitimes_get_current_instant( ) {
                           clock_gettime( CLOCK_MONOTONIC,&time);
                           return ( ( NANOSECONDS_PER_SECOND *
                                     (long)time.tv_sec ) + time.tv_nsec );
                        }
?
System.nanoTime()
Java Extension Trace
Java Extension Trace
% irb
>> require 'rubygems'
>> require 'hitimes'
Java Extension Trace
% irb lib/hitimes.rb
 % cat
>> require 'rubygems'
 ...
>> require 'hitimes'
 if RUBY_PLATFORM == "java" then
   require 'hitimes/hitimes'
 else
 ...
Java Extension Trace
% irb lib/hitimes.rb
 % cat
>> require 'rubygems'
 ...
>> require 'hitimes'
 if RUBY_PLATFORM == "java" then
   require 'hitimes/hitimes'
 else find ./lib -type f -name '*.jar'
     %
 ... ./lib/hitimes/hitimes.jar
Java Extension Trace
% irb lib/hitimes.rb
 % cat
>> require 'rubygems'
 ...
>> require 'hitimes'
 if RUBY_PLATFORM == "java" then
   require 'hitimes/hitimes'
 else find ./lib -type f -name '*.jar'
     %
 ... ./lib/hitimes/hitimes.jar

          % cat ext/java/src/hitimes/HitimesService.java
          package hitimes;
          [...]
          import org.jruby.runtime.load.BasicLibraryService;
          public class HitimesService implements BasicLibraryService {
              public boolean basicLoad( final Ruby runtime ) throws IOException {
                Hitimes.createHitimes( runtime );
                return true;
              }
          }
package hitimes;

@JRubyModule( name = "Hitimes" )
public class Hitimes {

   public static RubyModule createHitimes( Ruby runtime ) {
     RubyModule mHitimes = runtime.defineModule("Hitimes");

        RubyClass cStandardError = runtime.getStandardError();
        RubyClass cHitimesError = mHitimes.defineClassUnder("Error", cStandardError,
                                           cStandardError.getAllocator());

        RubyClass cHitimesStats = mHitimes.defineClassUnder("Stats",
                                   runtime.getObject(), HitimesStats.ALLOCATOR );
        cHitimesStats.defineAnnotatedMethods( HitimesStats.class );

        RubyClass cHitimesInterval = mHitimes.defineClassUnder("Interval",
                                       runtime.getObject(), HitimesInterval.ALLOCATOR );
        Hitimes.hitimesIntervalClass = cHitimesInterval;
        cHitimesInterval.defineAnnotatedMethods( HitimesInterval.class );
        return mHitimes;
    }
[...]
  }
Annotations
@JRubyClass( name = "Hitimes::Interval" )
public class HitimesInterval extends RubyObject {
...
    @JRubyMethod( name = "duration", alias = { "length", "to_f",
                    "to_seconds" } )
    public IRubyObject duration() { ... }

    @JRubyMethod( name = "started?" )
    public IRubyObject is_started() { ... }

    @JRubyMethod( name = "now", module = true )
    public static IRubyObject now( IRubyObject self ) { ... }

}
Annotations
@JRubyClass( name = "Hitimes::Interval" )
public class HitimesInterval extends RubyObject {
...
      @JRubyMethod( name = "measure", module = true, frame = true )
    public static IRubyObject measure( IRubyObject self, Block block ) {

         Ruby runtime = self.getRuntime();

          if ( block.isGiven() ) {
              IRubyObject        nil = runtime.getNil();
              ThreadContext context = runtime.getCurrentContext();
        [...]
              interval.start();
              block.yield( context, nil );
              interval.stop();

            return interval.duration();
         } else {
            throw Hitimes.newHitimesError( runtime, "No block given to Interval.measure" );
         }
    }
}
MRI - C Extension                                    JRuby - Java Extension

    require ‘hitimes/hitimes_ext                                require ‘hitimes/hitimes’
     lib/hitimes/hitimes_ext.so                                   lib/hitimes/hitimes.jar
                                                         public class HitimesService
                                                           implements BasicLibraryService {
         void Init_hitimes_ext()                             public boolean basicLoad( ... ) { ... }
                                                         }
mH = rb_define_module("Hitimes");                            RubyModule mHitimes = runtime.defineModule("Hitimes");
cH_Interval = rb_define_class_under( mH, "Interval",         RubyClass cHitimesInterval =
                                       rb_cObject );          mHitimes.defineClassUnder("Interval",
rb_define_alloc_func( cH_Interval, hitimes_interval_alloc );                         runtime.getObject(),
                                                                                    HitimesInterval.ALLOCATOR );
rb_define_module_function( cH_Interval, "measure",        cHitimesInterval.defineAnnotatedMethods(
                                                                                    HitimesInterval.class );
rb_define_method( cH_Interval,"duration", ... )
rb_define_method( cH_Interval,"started?", ... )           // Combined with the @JRubyMethod( name = ... )
rb_define_method( cH_Interval,"duration", ... )           // Annotations
...
JRuby - C Extensions
Jeremy Hinegardner
                                                     @copiousfreetime
                                              jeremy@hinegardner.org
   Thanks!                                  http://copiousfreetime.org



http://twitter.com/jruby/team

http://github.com/copiousfreetime/hitimes - Hitimes library

http://www.serabe.com/ - several blog posts jruby extensions
http://ola-bini.blogspot.com/2006/10/jruby-tutorial-4-writing-java.html
http://github.com/jruby/jruby/blob/master/src/org/jruby/runtime/load/
LoadService.java

http://tatice.deviantart.com/ - Operating System Icons

Mais conteúdo relacionado

Mais procurados

Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaCharles Nutter
 
Writing Ruby Extensions
Writing Ruby ExtensionsWriting Ruby Extensions
Writing Ruby ExtensionsMatt Todd
 
Flyweight Design Pattern
Flyweight Design PatternFlyweight Design Pattern
Flyweight Design PatternVarun MC
 
Spring RTS Engine Checkup
Spring RTS Engine CheckupSpring RTS Engine Checkup
Spring RTS Engine CheckupPVS-Studio
 
Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Charles Nutter
 
[GEG1] 10.camera-centric engine design for multithreaded rendering
[GEG1] 10.camera-centric engine design for multithreaded rendering[GEG1] 10.camera-centric engine design for multithreaded rendering
[GEG1] 10.camera-centric engine design for multithreaded rendering종빈 오
 
JavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesJavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesCharles Nutter
 
JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011Charles Nutter
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
Ruby Performance - The Last Mile - RubyConf India 2016
Ruby Performance - The Last Mile - RubyConf India 2016Ruby Performance - The Last Mile - RubyConf India 2016
Ruby Performance - The Last Mile - RubyConf India 2016Charles Nutter
 

Mais procurados (10)

Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
Writing Ruby Extensions
Writing Ruby ExtensionsWriting Ruby Extensions
Writing Ruby Extensions
 
Flyweight Design Pattern
Flyweight Design PatternFlyweight Design Pattern
Flyweight Design Pattern
 
Spring RTS Engine Checkup
Spring RTS Engine CheckupSpring RTS Engine Checkup
Spring RTS Engine Checkup
 
Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013
 
[GEG1] 10.camera-centric engine design for multithreaded rendering
[GEG1] 10.camera-centric engine design for multithreaded rendering[GEG1] 10.camera-centric engine design for multithreaded rendering
[GEG1] 10.camera-centric engine design for multithreaded rendering
 
JavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesJavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for Dummies
 
JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
Ruby Performance - The Last Mile - RubyConf India 2016
Ruby Performance - The Last Mile - RubyConf India 2016Ruby Performance - The Last Mile - RubyConf India 2016
Ruby Performance - The Last Mile - RubyConf India 2016
 

Semelhante a Extending JRuby

Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Nayden Gochev
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Taming client-server communication
Taming client-server communicationTaming client-server communication
Taming client-server communicationscothis
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to MissJava Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to MissAndres Almiray
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Invokedynamic / JSR-292
Invokedynamic / JSR-292Invokedynamic / JSR-292
Invokedynamic / JSR-292ytoshima
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011Lance Ball
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011Nick Sieger
 
JavaScript Robotics
JavaScript RoboticsJavaScript Robotics
JavaScript RoboticsAnna Gerber
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimizationxiaojueqq12345
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
Distributed Objects and JAVA
Distributed Objects and JAVADistributed Objects and JAVA
Distributed Objects and JAVAelliando dias
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes BackBurke Libbey
 
Jruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaJruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaKeith Bennett
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Jason Lotito
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 

Semelhante a Extending JRuby (20)

Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Taming client-server communication
Taming client-server communicationTaming client-server communication
Taming client-server communication
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to MissJava Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Java rmi
Java rmiJava rmi
Java rmi
 
Invokedynamic / JSR-292
Invokedynamic / JSR-292Invokedynamic / JSR-292
Invokedynamic / JSR-292
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
JavaScript Robotics
JavaScript RoboticsJavaScript Robotics
JavaScript Robotics
 
Message in a bottle
Message in a bottleMessage in a bottle
Message in a bottle
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimization
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Ruby on the JVM
Ruby on the JVMRuby on the JVM
Ruby on the JVM
 
Distributed Objects and JAVA
Distributed Objects and JAVADistributed Objects and JAVA
Distributed Objects and JAVA
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes Back
 
Jruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaJruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-java
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 

Mais de Jeremy Hinegardner

Mais de Jeremy Hinegardner (7)

Data Stories
Data StoriesData Stories
Data Stories
 
Creative Photography for Geeks
Creative Photography for GeeksCreative Photography for Geeks
Creative Photography for Geeks
 
Gemology
GemologyGemology
Gemology
 
FFI -- creating cross engine rubygems
FFI -- creating cross engine rubygemsFFI -- creating cross engine rubygems
FFI -- creating cross engine rubygems
 
Playing Nice with Others
Playing Nice with OthersPlaying Nice with Others
Playing Nice with Others
 
Crate - ruby based standalone executables
Crate - ruby based standalone executablesCrate - ruby based standalone executables
Crate - ruby based standalone executables
 
FFI - building cross engine ruby extensions
FFI - building cross engine ruby extensionsFFI - building cross engine ruby extensions
FFI - building cross engine ruby extensions
 

Último

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 

Último (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Extending JRuby

  • 7. Ruby Program Some Awesome Library sal.{dll,so,jar}
  • 8. Ruby Program Ruby Runtime Some Awesome Library sal.{dll,so,jar}
  • 9. Ruby Program Ruby Runtime Extension API Some Awesome Library sal.{dll,so,jar}
  • 10. Ruby Program Ruby Runtime Extension Extension API Some Awesome Library sal.{dll,so,jar}
  • 12. MRI - C Extensions
  • 13. How Many of You Have ... ... A C Extension
  • 14. How Many of You Have ... USED ... A C Extension
  • 15. How Many of You Have ... USED LOOKED AT THE SOURCE CODE OF ... A C Extension
  • 16. How Many of You Have ... USED LOOKED AT THE SOURCE CODE OF WRITTEN ... A C Extension
  • 18. C Extension Trace % irb >> require 'rubygems' >> require 'hitimes'
  • 19. C Extension Trace % irb >> require 'rubygems'| grep require % cat lib/hitimes.rb require 'hitimes/paths' >> require 'hitimes' require 'hitimes/version' require "hitimes/#{RUBY_VERSION.sub(/.d$/,'')}/hitimes_ext" ...
  • 20. C Extension Trace % irb >> require 'rubygems'| grep require % cat lib/hitimes.rb require 'hitimes/paths' >> require 'hitimes' require 'hitimes/version' require "hitimes/#{RUBY_VERSION.sub(/.d$/,'')}/hitimes_ext" % find ./lib -type f -name 'hitimes_ext*' ... ./lib/hitimes/1.8/hitimes_ext.bundle ...
  • 21. C Extension Trace % irb >> require 'rubygems'| grep require % cat lib/hitimes.rb require 'hitimes/paths' >> require 'hitimes' require 'hitimes/version' require "hitimes/#{RUBY_VERSION.sub(/.d$/,'')}/hitimes_ext" % find ./lib -type f -name 'hitimes_ext*' ... ./lib/hitimes/1.8/hitimes_ext.bundle ... % cat ext/hitimes/hitimes_ext.c void Init_hitimes_ext( ) { mH = rb_define_module("Hitimes"); eH_Error = rb_define_class_under(mH, "Error", rb_eStandardError); Init_hitimes_interval(); Init_hitimes_stats( ); }
  • 22. void Init_hitimes_interval() { mH = rb_define_module("Hitimes"); cH_Interval = rb_define_class_under( mH, "Interval", rb_cObject ); rb_define_alloc_func( cH_Interval, hitimes_interval_alloc ); rb_define_module_function( cH_Interval, "now", hitimes_interval_now, 0 ); rb_define_module_function( cH_Interval, "measure", hitimes_interval_measure, 0 ); rb_define_method( cH_Interval, "duration", hitimes_interval_duration, 0 ); rb_define_method( cH_Interval, "duration_so_far", hitimes_interval_duration_so_far, 0); rb_define_method( cH_Interval, "started?", hitimes_interval_started, 0 ); rb_define_method( cH_Interval, "running?", hitimes_interval_running, 0 ); rb_define_method( cH_Interval, "stopped?", hitimes_interval_stopped, 0 ); rb_define_method( cH_Interval, "start_instant", hitimes_interval_start_instant, 0 ); rb_define_method( cH_Interval, "stop_instant", hitimes_interval_stop_instant, 0 ); rb_define_method( cH_Interval, "start", hitimes_interval_start, 0); rb_define_method( cH_Interval, "stop", hitimes_interval_stop, 0); rb_define_method( cH_Interval, "split", hitimes_interval_split, 0); }
  • 23. JRuby - Java Extensions
  • 24. _WHY?
  • 27.
  • 28. hitimes_instant_t hitimes_get_current_instant() { LARGE_INTEGER tick; QueryPerformanceCounter(&tick); return (hitimes_instant_t)tick.QuadPart; }
  • 29. hitimes_instant_t hitimes_get_current_instant() { LARGE_INTEGER tick; QueryPerformanceCounter(&tick); return (hitimes_instant_t)tick.QuadPart; } hitimes_instant_t hitimes_get_current_instant( ) { Nanoseconds nano = AbsoluteToNanoseconds( UpTime() ); return *( hitimes_instant_t *)&nano; }
  • 30. hitimes_instant_t hitimes_get_current_instant() { LARGE_INTEGER tick; QueryPerformanceCounter(&tick); return (hitimes_instant_t)tick.QuadPart; } hitimes_instant_t hitimes_get_current_instant( ) { Nanoseconds nano = AbsoluteToNanoseconds( UpTime() ); return *( hitimes_instant_t *)&nano; } hitimes_instant_t hitimes_get_current_instant( ) { clock_gettime( CLOCK_MONOTONIC,&time); return ( ( NANOSECONDS_PER_SECOND * (long)time.tv_sec ) + time.tv_nsec ); }
  • 31. ?
  • 34. Java Extension Trace % irb >> require 'rubygems' >> require 'hitimes'
  • 35. Java Extension Trace % irb lib/hitimes.rb % cat >> require 'rubygems' ... >> require 'hitimes' if RUBY_PLATFORM == "java" then require 'hitimes/hitimes' else ...
  • 36. Java Extension Trace % irb lib/hitimes.rb % cat >> require 'rubygems' ... >> require 'hitimes' if RUBY_PLATFORM == "java" then require 'hitimes/hitimes' else find ./lib -type f -name '*.jar' % ... ./lib/hitimes/hitimes.jar
  • 37. Java Extension Trace % irb lib/hitimes.rb % cat >> require 'rubygems' ... >> require 'hitimes' if RUBY_PLATFORM == "java" then require 'hitimes/hitimes' else find ./lib -type f -name '*.jar' % ... ./lib/hitimes/hitimes.jar % cat ext/java/src/hitimes/HitimesService.java package hitimes; [...] import org.jruby.runtime.load.BasicLibraryService; public class HitimesService implements BasicLibraryService { public boolean basicLoad( final Ruby runtime ) throws IOException { Hitimes.createHitimes( runtime ); return true; } }
  • 38. package hitimes; @JRubyModule( name = "Hitimes" ) public class Hitimes { public static RubyModule createHitimes( Ruby runtime ) { RubyModule mHitimes = runtime.defineModule("Hitimes"); RubyClass cStandardError = runtime.getStandardError(); RubyClass cHitimesError = mHitimes.defineClassUnder("Error", cStandardError, cStandardError.getAllocator()); RubyClass cHitimesStats = mHitimes.defineClassUnder("Stats", runtime.getObject(), HitimesStats.ALLOCATOR ); cHitimesStats.defineAnnotatedMethods( HitimesStats.class ); RubyClass cHitimesInterval = mHitimes.defineClassUnder("Interval", runtime.getObject(), HitimesInterval.ALLOCATOR ); Hitimes.hitimesIntervalClass = cHitimesInterval; cHitimesInterval.defineAnnotatedMethods( HitimesInterval.class ); return mHitimes; } [...] }
  • 39. Annotations @JRubyClass( name = "Hitimes::Interval" ) public class HitimesInterval extends RubyObject { ... @JRubyMethod( name = "duration", alias = { "length", "to_f", "to_seconds" } ) public IRubyObject duration() { ... } @JRubyMethod( name = "started?" ) public IRubyObject is_started() { ... } @JRubyMethod( name = "now", module = true ) public static IRubyObject now( IRubyObject self ) { ... } }
  • 40. Annotations @JRubyClass( name = "Hitimes::Interval" ) public class HitimesInterval extends RubyObject { ... @JRubyMethod( name = "measure", module = true, frame = true ) public static IRubyObject measure( IRubyObject self, Block block ) { Ruby runtime = self.getRuntime(); if ( block.isGiven() ) { IRubyObject nil = runtime.getNil(); ThreadContext context = runtime.getCurrentContext(); [...] interval.start(); block.yield( context, nil ); interval.stop(); return interval.duration(); } else { throw Hitimes.newHitimesError( runtime, "No block given to Interval.measure" ); } } }
  • 41. MRI - C Extension JRuby - Java Extension require ‘hitimes/hitimes_ext require ‘hitimes/hitimes’ lib/hitimes/hitimes_ext.so lib/hitimes/hitimes.jar public class HitimesService implements BasicLibraryService { void Init_hitimes_ext() public boolean basicLoad( ... ) { ... } } mH = rb_define_module("Hitimes"); RubyModule mHitimes = runtime.defineModule("Hitimes"); cH_Interval = rb_define_class_under( mH, "Interval", RubyClass cHitimesInterval = rb_cObject ); mHitimes.defineClassUnder("Interval", rb_define_alloc_func( cH_Interval, hitimes_interval_alloc ); runtime.getObject(), HitimesInterval.ALLOCATOR ); rb_define_module_function( cH_Interval, "measure", cHitimesInterval.defineAnnotatedMethods( HitimesInterval.class ); rb_define_method( cH_Interval,"duration", ... ) rb_define_method( cH_Interval,"started?", ... ) // Combined with the @JRubyMethod( name = ... ) rb_define_method( cH_Interval,"duration", ... ) // Annotations ...
  • 42. JRuby - C Extensions
  • 43. Jeremy Hinegardner @copiousfreetime jeremy@hinegardner.org Thanks! http://copiousfreetime.org http://twitter.com/jruby/team http://github.com/copiousfreetime/hitimes - Hitimes library http://www.serabe.com/ - several blog posts jruby extensions http://ola-bini.blogspot.com/2006/10/jruby-tutorial-4-writing-java.html http://github.com/jruby/jruby/blob/master/src/org/jruby/runtime/load/ LoadService.java http://tatice.deviantart.com/ - Operating System Icons

Notas do Editor

  1. Ruby going on 10 years now Java stopped being my main programming language ~6-7 years ago. My latest Java in a Nutshell book, is brown and has a referee on the front. Java had a dot in its version at the time.
  2. have a program Need to access some functionality in a third party library, it is either to time consuming to write yourself, or its proprietary, or boring, or so solid no bugs in years. The extensions is what sits between the ruby runtime and exposes the funcationality of the Awesome Library to the ruby runtime so that your ruby program can use it.
  3. have a program Need to access some functionality in a third party library, it is either to time consuming to write yourself, or its proprietary, or boring, or so solid no bugs in years. The extensions is what sits between the ruby runtime and exposes the funcationality of the Awesome Library to the ruby runtime so that your ruby program can use it.
  4. have a program Need to access some functionality in a third party library, it is either to time consuming to write yourself, or its proprietary, or boring, or so solid no bugs in years. The extensions is what sits between the ruby runtime and exposes the funcationality of the Awesome Library to the ruby runtime so that your ruby program can use it.
  5. have a program Need to access some functionality in a third party library, it is either to time consuming to write yourself, or its proprietary, or boring, or so solid no bugs in years. The extensions is what sits between the ruby runtime and exposes the funcationality of the Awesome Library to the ruby runtime so that your ruby program can use it.
  6. Hi resolution timer library for recording performance metrics at the nanosecond resolution. To get nanosecond resolution, you need a very specific system call on ever operating system.
  7. Why would you want to take the time to create Java Extensions for use in Jruby? You can already easily utilize all the available Java libraries directly. You can make it more ruby-esque by writing a pure ruby wrapper around a Java API, as Thomas has pointed out. All in all, I would have to say, you would need a pretty compelling reason to do so.
  8. Hi resolution timer library for recording performance metrics at the nanosecond resolution. To get nanosecond resolution, you need a very specific system call on ever operating system.
  9. The initial require is the same but in JRuby, the hook leads us down a different path. JRuby looks for a .jar that is in the load path, and has the same path as the require Inside that .jar, the last item element of the require is converted from snake_case to ClassCase, and Service is tacked onto the end. That class is instantiated and the basicLoad method is called. This is your hook into the runtime. See the javadoc for LoadService.java
  10. The initial require is the same but in JRuby, the hook leads us down a different path. JRuby looks for a .jar that is in the load path, and has the same path as the require Inside that .jar, the last item element of the require is converted from snake_case to ClassCase, and Service is tacked onto the end. That class is instantiated and the basicLoad method is called. This is your hook into the runtime. See the javadoc for LoadService.java
  11. The initial require is the same but in JRuby, the hook leads us down a different path. JRuby looks for a .jar that is in the load path, and has the same path as the require Inside that .jar, the last item element of the require is converted from snake_case to ClassCase, and Service is tacked onto the end. That class is instantiated and the basicLoad method is called. This is your hook into the runtime. See the javadoc for LoadService.java
  12. The initial require is the same but in JRuby, the hook leads us down a different path. JRuby looks for a .jar that is in the load path, and has the same path as the require Inside that .jar, the last item element of the require is converted from snake_case to ClassCase, and Service is tacked onto the end. That class is instantiated and the basicLoad method is called. This is your hook into the runtime. See the javadoc for LoadService.java
  13. 1) Loading 2) Initialization 3) Class Hierarchy definition + Allocators 4) Method definition(s)
  14. Tim Felgentreff