SlideShare uma empresa Scribd logo
1 de 35
Thinking in C/C++, coding in Java
                     Thinking in C/C++, coding in Java

                                 foss.in 2012
                              Arvind Jayaprakash
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                      Audience
                     • Surely not for you if you’ve never done *nix
                       system programming or bare C/C++
                     • Maybe for you if you’ve done reasonable
                       amount of the above and “hello world” Java
                     • Prime audience if you are being pushed
                       into/want to explore Java as an option for
                       moderately high performance applications
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                    whoami
                                             Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                                finger
                     Home                          Work
                     • anomalizer                  • anomalizer



                     • anomalizer                  • http://inmobi.com/



                     • http://anomalizer.net/
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                        history/uname
                     Home                               Work
                     • MS-DOS in 1990                   • 5 years of FreeBSD & 1 year
                                                          of RHEL
                     • Primarily Win98 & a little bit
                       of RH7 in 2001                   • Chose the OS for current
                                                          employer’s servers (Ubuntu
                     • Win7 for PPT and Gentoo            since 2008)
                       for everything else in 2012
                       (fluxbox is my window
                       manager, xterm is my             • Gentoo/Win7 combo on my
                       favourite terminal)                laptop
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                    Primer
                                             Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                      Survival tips
                     • Java language (J2SE) != J2EE
                     • J2SE 5 (also known as 1.5 or JLS5) is lowest
                       respectable version of the language
                     • Sun (now Oracle) JRE continues to remain the
                       most popular free JRE+JDK
                     • Sun-JRE 1.6.0.22 is a good min version if you have
                       64 bit, x86_64, NUMA hardware running linux
                     • IDEs are necessary evil; vim/emacs just doesn’t
                       cut it
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                     Why Java 1.5?
                     •   Extensive concurrency libs
                     •   Generics
                     •   Annotations
                     •   Lint checks
                     •   Enums (typesafe too!)
                     •   Variable arguments
                     •   foreach
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                      Let us get started now*

                     * usually means over-simplification
                         that shall be clarified later
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                    Classes & Objects
                                                        Arvind Jayaprakash
Thinking in C/C++, coding in Java
             D’oh
                                    Arvind Jayaprakash
Thinking in C/C++, coding in Java
                               Primitives v/s objects
                     • Primitive data types, structs & classes play by
                       the exact same set of rules in C/C++ in almost
                       every context
                     • Java fundamentally drives a wedge between
                       the two both at a language level and runtime
                       level
                     • This is why there a primitive int and a class
                       Integer. These 2 are not interchangeable*
Arvind Jayaprakash




                                                        * Auto boxing is a deception
Thinking in C/C++, coding in Java
                              The approximate analogy
                     Primitives                         Composites (Objects)
                     • Think of primitives of values    • Think of objects (classes) as
                        that can reside on the stack      values that always* reside
                     • Lifespan always tied to            on heap
                        source scope for local          • Now it becomes obvious
                        variables                         that you are always dealing
                                                          with pointers/references
                                                        • It also becomes obvious
                                                          that their true lifespan is
                                                          not tied to source scope
Arvind Jayaprakash




                                                       *escape analysis implementations in some JVMs
Thinking in C/C++, coding in Java
                                 Nested structs/classes
                     class Point {                   struct Point {
                         public int x;                   int x;
                         public int y;                   int y;
                     }                               }

                     class Rect {                    struct InlineRect {
                        public Point top_left;           Point top_left;
                        public Point bottom_right;       Point bottom_right;
                     }                               }

                                                     struct IndirectRect {
                                                         Point *top_left;
                                                         Point *bottom_right;
                                                     }
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                       Null & void
                     • The notorious void* exists in Java; it is
                       commonly referred to as the class named
                       Object
                       – Any object (reference) can be directly cast to
                         Object
                       – An object (reference) of type Object can be
                         downcast to any type at compile time#
                     • null is not a type, however it is a language
                       defined literal (like true & false)
Arvind Jayaprakash




                                                        #   but can throw an error at runtime
Thinking in C/C++, coding in Java
                           What are references in java?
                     Why it is like a C pointer          Why it is not like a C++ reference
                     • Think of a reference as C         • j-refs are nullable (d’uh)
                       pointer                           • C++ refs cannot be made to
                     • Think of the dot operator in        point to something else
                       Java as C’s arrow operator          post declaration unlike Java
                     • null is NULL, dereferencing         refs
                       it is a bad idea                 • == operator in J has ptr
                     • Think of a final ref in Java as     equivalence semantics, not
                       a const ptr (not to be              dereferenced object
                       confused with ptr to const)         equivalence; use equals()
                                                           for that
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                             vtables
                     • Every class inherits from Object class
                     • Every member function is virtual in Java; there is
                       no opt-out
                        – Hence, internally, every class has a vtable
                        – And every object instance has an internal pointer/ref
                          to the vtable of its actual type (for dynamic dispatch)
                        – And a fn-call is via ptr-to-fn*
                     • RTTI (of C++ fame) comes at no additional cost as
                       a side-effect & guaranteed to be available
Arvind Jayaprakash




                                                    *Unless you do some class/method finalisation
Thinking in C/C++, coding in Java
                                    Other deceptive similarities
                                                                   Arvind Jayaprakash
Thinking in C/C++, coding in Java
                     Generics & templates aren’t the same

                     Java generics                    C++ templates
                     • No support for primitives      • Supports all types
                     • Single copy of code exists     • One copy of object code for
                        regardless of the number of     each template instantiation
                        type arguments a generic      • Glorified C style
                        code is used with               marcos, compilation happens
                                                        once for each expansion; some
                     • Generified code get              compilation errors crop up
                        compiled as an entity in        here
                        itself                        • No inheritance family based
                     • Bounded type                     bounding of type
                        parameters, possible, unbo      parameters, only explicit
                        unded defaults to Object        specialization is possible
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                           casts
                     • Syntactically identical to C casts
                     • Let us speak in C++ terms for semantic clarity
                       – static_cast is permitted
                       – No const_cast as there are no consts to begin with
                       – dynamic_cast permitted due to implicit RTTI
                         support (hence Object objects can be cast to
                         anything)
                       – reinterpret_cast disallowed; convert & copy is
                         the only way out
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                    Memory issues
                                                    Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                 Auto-boxing woes
                     • Java 5 made it syntactically possible to use a
                       primitive and it’s objectified version
                       interchange-able (eg: Long & long)
                     • The costs however are very different
                       – Indirection (ptr de-ref) to read value
                       – Memory footprint is 2 ptrs (one to value, and the
                         vptr inside object) + that of actually storing the
                         primitive
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                          You don’t want to see this
                     Integer x;

                     for(int i = 0 ; i < 100; i++) {
                         x = i * i;
                     }
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                           int[] v/s ArrayList<Integer>
                     • vector<int> & int[] have identical performance
                       in C++, don’t carry that assumption into Java!
                     • Remember, generics only work with
                       objects, so we can’t use an int with it
                     • And int is just not the same as an Integer
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                                        In figures
                     int[]          Array header   a0   a1    a2      an-1




                     ArrayList<Integer>

                     Array header



                                        Object                               Object
                                        Header                               Header
                             Object                          Object
                                           a2                                 an-1
                             Header                          Header
Arvind Jayaprakash




                               a0                              a1
Thinking in C/C++, coding in Java
                                      In words
                     • On an un-tuned 64 bit JVM, pay at-least 400%
                       memory tax (it is still 200% on a tuned JVM)
                     • 100% apparent memory access cost
                     • Completely wreck your cache lines by simply
                       iterating through the array (real tax can
                       exceed 100%)
                     • And yes, there is copying involved when you
                       expand beyond a certain limit
                     • And more work for GC …
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                     The solution
                     • So what about collections of primitives?
                       – What if you want an expandable array of ints?
                       – What if you want a map of short to double?
                     • Use primitive collection libraries
                       – trove4j solves the above problems
                       – It is GNU project & comes with LGPL license too 
                     • The larger point however is to understand the
                       object model & memory layout
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                          No reinterpret cast for you!
                     • Imagine trying to read values from byte
                       streams such as files & sockets
                     • You have 3 choices
                       – Bottom-up read, one primitive at a time (entire
                         class chain must play nice for this)
                       – Slurp the blob, break the blob and make
                         meaningful object by copying over the primitives
                         in top-down fashion (a.k.a. memcpy)
                       – Use java serialization (disallows conditional
                         parsing)
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                    I/O ops
                                              Arvind Jayaprakash
Thinking in C/C++, coding in Java
                               Dealing with slow parts
                                 (of any language)
                     • A common reason to fall back to “native”
                       languages is when a large amount of I/O is
                       involved
                     • I/O is dreaded as it usually translates to *nix
                       syscalls
                     • A lot of syscalls exist specifically to optimize
                       userspace/kernel space transition
                       inefficiencies
                     • They also have OS idosyncracies
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                                   Java & I/O
                      *nix & C feature             Java equivalent                 Available since
                     Allocate char*      ByteBuffer.allocate()               1.4
                     sendfile()          FileChannel.transfer{To|From}       1.4
                     mmap()              FileChannel.map()                   1.4
                     epoll()             Channels.Selector() +               API since 1.4, epoll as
                                         SelectorProvider                    implementation since 1.6
                     readv()/writev()    Channel.read/write (ByteBuffer[])   1.4
                     chmod()/chown()/ NIO2 file api                          1.7
                     inotify()/stat()/
                     copy()/symlink()/
                     readdir/…
                     SCTP                -                                   1.7
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                    etc
                                          Arvind Jayaprakash
Thinking in C/C++, coding in Java
                              Not covered in the talk
                     • Reflection
                       – Runtime inspection of types & dynamic code gen
                     • JIT
                       – JRE profiles applications & recompiles code with
                         optimizations mid-flight!
                       – Discovers structural shortcuts possible in a given
                         app & exploits it
                     • JNI
                       – When you have to bridge your C code
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                          Go read about the following
                     • “maven” (awesome build mgmt tool)
                     • “Google guavas” (as important as boost for
                       cpp, historically speaking)
                     • “Project lombok” (uses annotations to tuck
                       away massive boilerplate coding)
                     • “slf4j” (log4j is so Java 1.2, never code against
                       it)
                     • “netty” (the libevent of Java)
Arvind Jayaprakash
Thinking in C/C++, coding in Java
                                   And some more
                     • “testng” (unit & module testing system)
                     • “mockito” (helps in creating test mocks)
                     • “javassist” (create entire classes from strings
                       at runtime!)
                     • “guice” & “Spring DI” (dependency injection)
Arvind Jayaprakash

Mais conteúdo relacionado

Destaque

ITFT - Java Coding
ITFT - Java CodingITFT - Java Coding
ITFT - Java CodingBlossom Sood
 
Secure Coding for Java - An introduction
Secure Coding for Java - An introductionSecure Coding for Java - An introduction
Secure Coding for Java - An introductionSebastien Gioria
 
Functions ppt ch06
Functions ppt ch06Functions ppt ch06
Functions ppt ch06Terry Yoast
 
Presentation on Online Admission System (OAS)
Presentation on Online Admission System (OAS)Presentation on Online Admission System (OAS)
Presentation on Online Admission System (OAS)Tanvir Ahmad
 
9781285852744 ppt ch08
9781285852744 ppt ch089781285852744 ppt ch08
9781285852744 ppt ch08Terry Yoast
 
9781285852744 ppt ch01
9781285852744 ppt ch019781285852744 ppt ch01
9781285852744 ppt ch01Terry Yoast
 
9781285852744 ppt ch09
9781285852744 ppt ch099781285852744 ppt ch09
9781285852744 ppt ch09Terry Yoast
 
9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02Terry Yoast
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A ReviewFernando Torres
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Javayht4ever
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01Adil Kakakhel
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental PrinciplesIntro C# Book
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.pptTareq Hasan
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 

Destaque (17)

ITFT - Java Coding
ITFT - Java CodingITFT - Java Coding
ITFT - Java Coding
 
Chap 1 c++
Chap 1 c++Chap 1 c++
Chap 1 c++
 
Secure Coding for Java - An introduction
Secure Coding for Java - An introductionSecure Coding for Java - An introduction
Secure Coding for Java - An introduction
 
Functions ppt ch06
Functions ppt ch06Functions ppt ch06
Functions ppt ch06
 
Virtual Classroom
Virtual ClassroomVirtual Classroom
Virtual Classroom
 
Presentation on Online Admission System (OAS)
Presentation on Online Admission System (OAS)Presentation on Online Admission System (OAS)
Presentation on Online Admission System (OAS)
 
9781285852744 ppt ch08
9781285852744 ppt ch089781285852744 ppt ch08
9781285852744 ppt ch08
 
9781285852744 ppt ch01
9781285852744 ppt ch019781285852744 ppt ch01
9781285852744 ppt ch01
 
9781285852744 ppt ch09
9781285852744 ppt ch099781285852744 ppt ch09
9781285852744 ppt ch09
 
9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 

Semelhante a Thinking in C/C++, coding in Java

Chapter-1 Introduction.pptx
Chapter-1 Introduction.pptxChapter-1 Introduction.pptx
Chapter-1 Introduction.pptxSumanBhandari40
 
Introduction to java by priti sajja
Introduction to java by priti sajjaIntroduction to java by priti sajja
Introduction to java by priti sajjaPriti Srinivas Sajja
 
Expert JavaScript Programming
Expert JavaScript ProgrammingExpert JavaScript Programming
Expert JavaScript ProgrammingYoshiki Shibukawa
 
PyData Frankfurt - (Efficient) Data Exchange with "Foreign" Ecosystems
PyData Frankfurt - (Efficient) Data Exchange with "Foreign" EcosystemsPyData Frankfurt - (Efficient) Data Exchange with "Foreign" Ecosystems
PyData Frankfurt - (Efficient) Data Exchange with "Foreign" EcosystemsUwe Korn
 
Fundamentals of java --- version 2
Fundamentals of java --- version 2Fundamentals of java --- version 2
Fundamentals of java --- version 2Uday Sharma
 
Polyglot Plugin Programming
Polyglot Plugin ProgrammingPolyglot Plugin Programming
Polyglot Plugin ProgrammingAtlassian
 
Difference between java and c#
Difference between java and c#Difference between java and c#
Difference between java and c#TECOS
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaattiqrocket
 

Semelhante a Thinking in C/C++, coding in Java (20)

9 cm604.1
9 cm604.19 cm604.1
9 cm604.1
 
Chapter-1 Introduction.pptx
Chapter-1 Introduction.pptxChapter-1 Introduction.pptx
Chapter-1 Introduction.pptx
 
Introduction to java by priti sajja
Introduction to java by priti sajjaIntroduction to java by priti sajja
Introduction to java by priti sajja
 
JAVA INTRODUCTION
JAVA INTRODUCTIONJAVA INTRODUCTION
JAVA INTRODUCTION
 
Expert JavaScript Programming
Expert JavaScript ProgrammingExpert JavaScript Programming
Expert JavaScript Programming
 
PyData Frankfurt - (Efficient) Data Exchange with "Foreign" Ecosystems
PyData Frankfurt - (Efficient) Data Exchange with "Foreign" EcosystemsPyData Frankfurt - (Efficient) Data Exchange with "Foreign" Ecosystems
PyData Frankfurt - (Efficient) Data Exchange with "Foreign" Ecosystems
 
Ndk
NdkNdk
Ndk
 
Java features
Java featuresJava features
Java features
 
Fundamentals of java --- version 2
Fundamentals of java --- version 2Fundamentals of java --- version 2
Fundamentals of java --- version 2
 
Java Starting
Java StartingJava Starting
Java Starting
 
Polyglot Plugin Programming
Polyglot Plugin ProgrammingPolyglot Plugin Programming
Polyglot Plugin Programming
 
Difference between java and c#
Difference between java and c#Difference between java and c#
Difference between java and c#
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 
01intro
01intro01intro
01intro
 
Lesson1 intro
Lesson1 introLesson1 intro
Lesson1 intro
 
Lesson1 intro
Lesson1 introLesson1 intro
Lesson1 intro
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Jax keynote
Jax keynoteJax keynote
Jax keynote
 
RenderScript
RenderScriptRenderScript
RenderScript
 
Euruko 2012 - JRuby
Euruko 2012 - JRubyEuruko 2012 - JRuby
Euruko 2012 - JRuby
 

Thinking in C/C++, coding in Java

  • 1. Thinking in C/C++, coding in Java Thinking in C/C++, coding in Java foss.in 2012 Arvind Jayaprakash Arvind Jayaprakash
  • 2. Thinking in C/C++, coding in Java Audience • Surely not for you if you’ve never done *nix system programming or bare C/C++ • Maybe for you if you’ve done reasonable amount of the above and “hello world” Java • Prime audience if you are being pushed into/want to explore Java as an option for moderately high performance applications Arvind Jayaprakash
  • 3. Thinking in C/C++, coding in Java whoami Arvind Jayaprakash
  • 4. Thinking in C/C++, coding in Java finger Home Work • anomalizer • anomalizer • anomalizer • http://inmobi.com/ • http://anomalizer.net/ Arvind Jayaprakash
  • 5. Thinking in C/C++, coding in Java history/uname Home Work • MS-DOS in 1990 • 5 years of FreeBSD & 1 year of RHEL • Primarily Win98 & a little bit of RH7 in 2001 • Chose the OS for current employer’s servers (Ubuntu • Win7 for PPT and Gentoo since 2008) for everything else in 2012 (fluxbox is my window manager, xterm is my • Gentoo/Win7 combo on my favourite terminal) laptop Arvind Jayaprakash
  • 6. Thinking in C/C++, coding in Java Primer Arvind Jayaprakash
  • 7. Thinking in C/C++, coding in Java Survival tips • Java language (J2SE) != J2EE • J2SE 5 (also known as 1.5 or JLS5) is lowest respectable version of the language • Sun (now Oracle) JRE continues to remain the most popular free JRE+JDK • Sun-JRE 1.6.0.22 is a good min version if you have 64 bit, x86_64, NUMA hardware running linux • IDEs are necessary evil; vim/emacs just doesn’t cut it Arvind Jayaprakash
  • 8. Thinking in C/C++, coding in Java Why Java 1.5? • Extensive concurrency libs • Generics • Annotations • Lint checks • Enums (typesafe too!) • Variable arguments • foreach Arvind Jayaprakash
  • 9. Thinking in C/C++, coding in Java Let us get started now* * usually means over-simplification that shall be clarified later Arvind Jayaprakash
  • 10. Thinking in C/C++, coding in Java Classes & Objects Arvind Jayaprakash
  • 11. Thinking in C/C++, coding in Java D’oh Arvind Jayaprakash
  • 12. Thinking in C/C++, coding in Java Primitives v/s objects • Primitive data types, structs & classes play by the exact same set of rules in C/C++ in almost every context • Java fundamentally drives a wedge between the two both at a language level and runtime level • This is why there a primitive int and a class Integer. These 2 are not interchangeable* Arvind Jayaprakash * Auto boxing is a deception
  • 13. Thinking in C/C++, coding in Java The approximate analogy Primitives Composites (Objects) • Think of primitives of values • Think of objects (classes) as that can reside on the stack values that always* reside • Lifespan always tied to on heap source scope for local • Now it becomes obvious variables that you are always dealing with pointers/references • It also becomes obvious that their true lifespan is not tied to source scope Arvind Jayaprakash *escape analysis implementations in some JVMs
  • 14. Thinking in C/C++, coding in Java Nested structs/classes class Point { struct Point { public int x; int x; public int y; int y; } } class Rect { struct InlineRect { public Point top_left; Point top_left; public Point bottom_right; Point bottom_right; } } struct IndirectRect { Point *top_left; Point *bottom_right; } Arvind Jayaprakash
  • 15. Thinking in C/C++, coding in Java Null & void • The notorious void* exists in Java; it is commonly referred to as the class named Object – Any object (reference) can be directly cast to Object – An object (reference) of type Object can be downcast to any type at compile time# • null is not a type, however it is a language defined literal (like true & false) Arvind Jayaprakash # but can throw an error at runtime
  • 16. Thinking in C/C++, coding in Java What are references in java? Why it is like a C pointer Why it is not like a C++ reference • Think of a reference as C • j-refs are nullable (d’uh) pointer • C++ refs cannot be made to • Think of the dot operator in point to something else Java as C’s arrow operator post declaration unlike Java • null is NULL, dereferencing refs it is a bad idea  • == operator in J has ptr • Think of a final ref in Java as equivalence semantics, not a const ptr (not to be dereferenced object confused with ptr to const) equivalence; use equals() for that Arvind Jayaprakash
  • 17. Thinking in C/C++, coding in Java vtables • Every class inherits from Object class • Every member function is virtual in Java; there is no opt-out – Hence, internally, every class has a vtable – And every object instance has an internal pointer/ref to the vtable of its actual type (for dynamic dispatch) – And a fn-call is via ptr-to-fn* • RTTI (of C++ fame) comes at no additional cost as a side-effect & guaranteed to be available Arvind Jayaprakash *Unless you do some class/method finalisation
  • 18. Thinking in C/C++, coding in Java Other deceptive similarities Arvind Jayaprakash
  • 19. Thinking in C/C++, coding in Java Generics & templates aren’t the same Java generics C++ templates • No support for primitives • Supports all types • Single copy of code exists • One copy of object code for regardless of the number of each template instantiation type arguments a generic • Glorified C style code is used with marcos, compilation happens once for each expansion; some • Generified code get compilation errors crop up compiled as an entity in here itself • No inheritance family based • Bounded type bounding of type parameters, possible, unbo parameters, only explicit unded defaults to Object specialization is possible Arvind Jayaprakash
  • 20. Thinking in C/C++, coding in Java casts • Syntactically identical to C casts • Let us speak in C++ terms for semantic clarity – static_cast is permitted – No const_cast as there are no consts to begin with – dynamic_cast permitted due to implicit RTTI support (hence Object objects can be cast to anything) – reinterpret_cast disallowed; convert & copy is the only way out Arvind Jayaprakash
  • 21. Thinking in C/C++, coding in Java Memory issues Arvind Jayaprakash
  • 22. Thinking in C/C++, coding in Java Auto-boxing woes • Java 5 made it syntactically possible to use a primitive and it’s objectified version interchange-able (eg: Long & long) • The costs however are very different – Indirection (ptr de-ref) to read value – Memory footprint is 2 ptrs (one to value, and the vptr inside object) + that of actually storing the primitive Arvind Jayaprakash
  • 23. Thinking in C/C++, coding in Java You don’t want to see this Integer x; for(int i = 0 ; i < 100; i++) { x = i * i; } Arvind Jayaprakash
  • 24. Thinking in C/C++, coding in Java int[] v/s ArrayList<Integer> • vector<int> & int[] have identical performance in C++, don’t carry that assumption into Java! • Remember, generics only work with objects, so we can’t use an int with it • And int is just not the same as an Integer Arvind Jayaprakash
  • 25. Thinking in C/C++, coding in Java In figures int[] Array header a0 a1 a2 an-1 ArrayList<Integer> Array header Object Object Header Header Object Object a2 an-1 Header Header Arvind Jayaprakash a0 a1
  • 26. Thinking in C/C++, coding in Java In words • On an un-tuned 64 bit JVM, pay at-least 400% memory tax (it is still 200% on a tuned JVM) • 100% apparent memory access cost • Completely wreck your cache lines by simply iterating through the array (real tax can exceed 100%) • And yes, there is copying involved when you expand beyond a certain limit • And more work for GC … Arvind Jayaprakash
  • 27. Thinking in C/C++, coding in Java The solution • So what about collections of primitives? – What if you want an expandable array of ints? – What if you want a map of short to double? • Use primitive collection libraries – trove4j solves the above problems – It is GNU project & comes with LGPL license too  • The larger point however is to understand the object model & memory layout Arvind Jayaprakash
  • 28. Thinking in C/C++, coding in Java No reinterpret cast for you! • Imagine trying to read values from byte streams such as files & sockets • You have 3 choices – Bottom-up read, one primitive at a time (entire class chain must play nice for this) – Slurp the blob, break the blob and make meaningful object by copying over the primitives in top-down fashion (a.k.a. memcpy) – Use java serialization (disallows conditional parsing) Arvind Jayaprakash
  • 29. Thinking in C/C++, coding in Java I/O ops Arvind Jayaprakash
  • 30. Thinking in C/C++, coding in Java Dealing with slow parts (of any language) • A common reason to fall back to “native” languages is when a large amount of I/O is involved • I/O is dreaded as it usually translates to *nix syscalls • A lot of syscalls exist specifically to optimize userspace/kernel space transition inefficiencies • They also have OS idosyncracies Arvind Jayaprakash
  • 31. Thinking in C/C++, coding in Java Java & I/O *nix & C feature Java equivalent Available since Allocate char* ByteBuffer.allocate() 1.4 sendfile() FileChannel.transfer{To|From} 1.4 mmap() FileChannel.map() 1.4 epoll() Channels.Selector() + API since 1.4, epoll as SelectorProvider implementation since 1.6 readv()/writev() Channel.read/write (ByteBuffer[]) 1.4 chmod()/chown()/ NIO2 file api 1.7 inotify()/stat()/ copy()/symlink()/ readdir/… SCTP - 1.7 Arvind Jayaprakash
  • 32. Thinking in C/C++, coding in Java etc Arvind Jayaprakash
  • 33. Thinking in C/C++, coding in Java Not covered in the talk • Reflection – Runtime inspection of types & dynamic code gen • JIT – JRE profiles applications & recompiles code with optimizations mid-flight! – Discovers structural shortcuts possible in a given app & exploits it • JNI – When you have to bridge your C code Arvind Jayaprakash
  • 34. Thinking in C/C++, coding in Java Go read about the following • “maven” (awesome build mgmt tool) • “Google guavas” (as important as boost for cpp, historically speaking) • “Project lombok” (uses annotations to tuck away massive boilerplate coding) • “slf4j” (log4j is so Java 1.2, never code against it) • “netty” (the libevent of Java) Arvind Jayaprakash
  • 35. Thinking in C/C++, coding in Java And some more • “testng” (unit & module testing system) • “mockito” (helps in creating test mocks) • “javassist” (create entire classes from strings at runtime!) • “guice” & “Spring DI” (dependency injection) Arvind Jayaprakash

Notas do Editor

  1. Minute #4
  2. Minute #9
  3. Target minute #18
  4. Target minute #23
  5. Minute 29
  6. Target minute #36
  7. Target minute #40