SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

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
 

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Plus de Jeremy Hinegardner

Plus 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
 

Dernier

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Dernier (20)

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

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

Notes de l'éditeur

  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