SlideShare une entreprise Scribd logo
1  sur  45
Télécharger pour lire hors ligne
Unsafe Java




              Misha Kozik
                @mishadoff
Average C developer
Java is Safe!
          ●   No pointers
          ●   No direct memory allocation
          ●   Compile-time checking
          ●   Platform-independent types
          ●   Checked Exceptions
          ●   Garbage collection
          ●   etc.
Not really...
Not really...

          sun.misc.Unsafe
“API” Overview
Info                           Synchronization
  ●   addressSize                ●   monitorEnter
  ●   pageSize                   ●   tryMonitorEnter
                                 ●   monitorExit
Objects                          ●   compareAndSwapInt
  ●   allocateInstance
                                 ●   putOrderedInt
  ●   objectFieldOffset
                                 ●   park
                                 ●   unpark
Classes
  ●   staticFieldOffset        Memory
  ●   defineClass                ●   allocateMemory
  ●   defineAnonymousClass       ●   copyMemory
  ●   ensureClassInitialized     ●   freeMemory
                                 ●   getAddress
Arrays                           ●   getInt
  ●   arrayBaseOffset            ●   putInt
  ●   arrayIndexScale


                                                         TOTAL: 105
Instantiation
“Trusted” code with bootloader




java -Xbootclasspath:/usr/jdk1.7.0/jre/lib/rt.jar:.
com.mishadoff.magic.UnsafeClient
Reflection
Usage
Avoid Initialization
Memory Corruption
#define TRUE FALSE
Very Unchecked Cast
Dynamic Classes
sizeOf
sizeOf
Shallow Copy
Hide Password
Throw Exception
Fast Serialization

● Serializable (so slooooow)
● Externalizable (requires schema)

● protobuf (dependency)

● kryo (dependency)

● Unsafe
Fast Serialization: Write
Fast Serialization: Read
Fast Serialization: Performance




Benchmarks:   https://github.com/eishay/jvm-serializers/wiki
Super Array
Off-heap Collections

● Not limited to Heap capacity
● Not limited to Integer.MAX_VALUE size

● No boundary checks

● Not under GC management

● Partially available at java.nio.*

● Useful for math computations

● Realtime programming




        “The price of greatness is responsibility.”
                             – Winston Churchill
Concurrency
Concurrency: Client
Concurrency: Stupid Counter
Concurrency: Stupid Counter




               Counter result: 99542945
                Time passed in ms: 679
Concurrency: Sync Counter
Concurrency: Sync Counter




             Counter result: 100000000
             Time passed in ms: 10136
Concurrency: Lock Counter
Concurrency: Lock Counter




             Counter result: 100000000
             Time passed in ms: 8065
Concurrency: Atomic Counter
Concurrency: Atomic Counter




              Counter result: 100000000
              Time passed in ms: 6552
Concurrency: CAS Counter
   CAS = Compare And Swap
Concurrency: CAS Counter
   CAS = Compare And Swap




               Counter result: 100000000
               Time passed in ms: 6454
Lock-free Data Structures
     Intuition
 ● Create a copy of current state
 ● Modify it

 ● CAS

 ● Repeat if it fails




 Problems
 ● Hard to implement.
 ● Problem ABA (DCAS, LL/SC)

 ● Reordering (Memory Barriers)
And finally...
Unsafe.park()

“Block current thread, returning when a balancing
unpark occurs, or a balancing unpark has already
occurred, or the thread is interrupted, or, if not
absolute and time is not zero, the given time
nanoseconds have elapsed, or if absolute, the given
deadline in milliseconds since Epoch has passed, or
spuriously (i.e., returning for no "reason"). Note:
This operation is in the Unsafe class only because
unpark is, so it would be strange to place it
elsewhere.”
                                        – Javadoc
Disclaimer
● May be removed/changed
● Not portable

● Depends on architecture

● Depends on JVM implementation

● Depends on major/minor JVM

● Never use it in production




             Gentle reminder:
             One error may cause
             JVM crash
Projects

Project Lambda
Project Jigsaw
Links
●   Javadoc http://www.docjar.com/docs/api/sun/misc/Unsafe.html
●   My Blog http://mishadoff.github.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/
●   Tricks with Direct Memory Access
    http://highlyscalable.wordpress.com/2012/02/02/direct-memory-access-in-java/

●   StackOverflow http://stackoverflow.com/questions/5574241/interesting-uses-of-sun-misc-unsafe
●   Native C/C++ Like Performance For Java Object Serialisation
    http://mechanical-sympathy.blogspot.de/2012/07/native-cc-like-performance-for-java.html

●   Big Arrays in Java http://www.omsn.de/blog/big-arrays-in-java
●   Lock-Free Wait-Free Hash Table
    http://www.azulsystems.com/about_us/presentations/lock-free-hash

●   Java theory and practice: Going atomic
    www.ibm.com/developerworks/java/library/j-jtp11234/

●   Fast multipurpose serialization (RU) http://www.javaspecialist.ru/2012/07/blog-post.html
Thanks!
 Q?

Contenu connexe

Tendances

Site Testing with CasperJS
Site Testing with CasperJSSite Testing with CasperJS
Site Testing with CasperJS
Joseph Scott
 
Server::Starter meets Java
Server::Starter meets JavaServer::Starter meets Java
Server::Starter meets Java
Tokuhiro Matsuno
 
casperjs presentation
 casperjs presentation casperjs presentation
casperjs presentation
AnsviaLab
 

Tendances (18)

Nightwatch 101 - Salvador Molina
Nightwatch 101 - Salvador MolinaNightwatch 101 - Salvador Molina
Nightwatch 101 - Salvador Molina
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
 
Unit Testing With Javascript
Unit Testing With JavascriptUnit Testing With Javascript
Unit Testing With Javascript
 
Threejs使ってみた
Threejs使ってみたThreejs使ってみた
Threejs使ってみた
 
Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)
 
From dot net_to_rails
From dot net_to_railsFrom dot net_to_rails
From dot net_to_rails
 
Site Testing with CasperJS
Site Testing with CasperJSSite Testing with CasperJS
Site Testing with CasperJS
 
Survive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksSurvive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and Tricks
 
Nodejs web service for starters
Nodejs web service for startersNodejs web service for starters
Nodejs web service for starters
 
Transactions and Concurrency Control Patterns
Transactions and Concurrency Control PatternsTransactions and Concurrency Control Patterns
Transactions and Concurrency Control Patterns
 
Perl6 meets JVM
Perl6 meets JVMPerl6 meets JVM
Perl6 meets JVM
 
Being agile with modern Java
Being agile with modern JavaBeing agile with modern Java
Being agile with modern Java
 
Server::Starter meets Java
Server::Starter meets JavaServer::Starter meets Java
Server::Starter meets Java
 
casperjs presentation
 casperjs presentation casperjs presentation
casperjs presentation
 
JavaScript Testing: Mocha + Chai
JavaScript Testing: Mocha + ChaiJavaScript Testing: Mocha + Chai
JavaScript Testing: Mocha + Chai
 
Transactions and Concurrency Control Patterns - 2019
Transactions and Concurrency Control Patterns - 2019Transactions and Concurrency Control Patterns - 2019
Transactions and Concurrency Control Patterns - 2019
 
CasperJS and PhantomJS for Automated Testing
CasperJS and PhantomJS for Automated TestingCasperJS and PhantomJS for Automated Testing
CasperJS and PhantomJS for Automated Testing
 
The Rust Programming Language
The Rust Programming LanguageThe Rust Programming Language
The Rust Programming Language
 

En vedette

Spring test mvc 발표자료
Spring test mvc 발표자료Spring test mvc 발표자료
Spring test mvc 발표자료
수홍 이
 

En vedette (20)

A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Do we need Unsafe in Java?
Do we need Unsafe in Java?Do we need Unsafe in Java?
Do we need Unsafe in Java?
 
Java Memory Management Tricks
Java Memory Management Tricks Java Memory Management Tricks
Java Memory Management Tricks
 
20141206 4 q14_dataconference_i_am_your_db
20141206 4 q14_dataconference_i_am_your_db20141206 4 q14_dataconference_i_am_your_db
20141206 4 q14_dataconference_i_am_your_db
 
김용하 - 아프니까 지름이다
김용하 - 아프니까 지름이다김용하 - 아프니까 지름이다
김용하 - 아프니까 지름이다
 
Care for the sea
Care for the seaCare for the sea
Care for the sea
 
정동현 - 고기를 잘 굽는 법
정동현 - 고기를 잘 굽는 법정동현 - 고기를 잘 굽는 법
정동현 - 고기를 잘 굽는 법
 
Java GC, Off-heap workshop
Java GC, Off-heap workshopJava GC, Off-heap workshop
Java GC, Off-heap workshop
 
웹을 지탱하는 기술
웹을 지탱하는 기술웹을 지탱하는 기술
웹을 지탱하는 기술
 
On heap cache vs off-heap cache
On heap cache vs off-heap cacheOn heap cache vs off-heap cache
On heap cache vs off-heap cache
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
 
Top Reasons Why Java Rocks (report preview) - http:0t.ee/java-rocks
Top Reasons Why Java Rocks (report preview) - http:0t.ee/java-rocksTop Reasons Why Java Rocks (report preview) - http:0t.ee/java-rocks
Top Reasons Why Java Rocks (report preview) - http:0t.ee/java-rocks
 
Whitebase : Assault Carrier for Micro-Services
Whitebase : Assault Carrier for Micro-ServicesWhitebase : Assault Carrier for Micro-Services
Whitebase : Assault Carrier for Micro-Services
 
적당한 스터디 발표자료 만들기 2.0
적당한 스터디 발표자료 만들기 2.0적당한 스터디 발표자료 만들기 2.0
적당한 스터디 발표자료 만들기 2.0
 
Spring test mvc 발표자료
Spring test mvc 발표자료Spring test mvc 발표자료
Spring test mvc 발표자료
 
Docker 간단 개념 / Docker 를 이용한 MSA 기반의 Spring Boot 프로젝트 - DSmentoring 정다운
Docker 간단 개념 / Docker 를 이용한 MSA 기반의 Spring Boot 프로젝트 - DSmentoring 정다운Docker 간단 개념 / Docker 를 이용한 MSA 기반의 Spring Boot 프로젝트 - DSmentoring 정다운
Docker 간단 개념 / Docker 를 이용한 MSA 기반의 Spring Boot 프로젝트 - DSmentoring 정다운
 
Memory Management: What You Need to Know When Moving to Java 8
Memory Management: What You Need to Know When Moving to Java 8Memory Management: What You Need to Know When Moving to Java 8
Memory Management: What You Need to Know When Moving to Java 8
 
지금 핫한 Real-time In-memory Stream Processing 이야기
지금 핫한 Real-time In-memory Stream Processing 이야기지금 핫한 Real-time In-memory Stream Processing 이야기
지금 핫한 Real-time In-memory Stream Processing 이야기
 
A look under the hood at Apache Spark's API and engine evolutions
A look under the hood at Apache Spark's API and engine evolutionsA look under the hood at Apache Spark's API and engine evolutions
A look under the hood at Apache Spark's API and engine evolutions
 
java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰
 

Similaire à Unsafe Java

JVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir IvanovJVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir Ivanov
ZeroTurnaround
 
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
Vladimir Ivanov
 
Deployments with rails
Deployments with railsDeployments with rails
Deployments with rails
Gourav Tiwari
 

Similaire à Unsafe Java (20)

Multithreading in Node.js and JavaScript
Multithreading in Node.js and JavaScriptMultithreading in Node.js and JavaScript
Multithreading in Node.js and JavaScript
 
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
 
JVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir IvanovJVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir Ivanov
 
The Automation Factory
The Automation FactoryThe Automation Factory
The Automation Factory
 
Session - Debugging memory stomps and other atrocities - Stefan Reinalter - T...
Session - Debugging memory stomps and other atrocities - Stefan Reinalter - T...Session - Debugging memory stomps and other atrocities - Stefan Reinalter - T...
Session - Debugging memory stomps and other atrocities - Stefan Reinalter - T...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
NetflixOSS Open House Lightning talks
NetflixOSS Open House Lightning talksNetflixOSS Open House Lightning talks
NetflixOSS Open House Lightning talks
 
DCSF19 Docker Containers & Java: What I Wish I Had Been Told
DCSF19 Docker Containers & Java: What I Wish I Had Been ToldDCSF19 Docker Containers & Java: What I Wish I Had Been Told
DCSF19 Docker Containers & Java: What I Wish I Had Been Told
 
Fight with Metaspace OOM
Fight with Metaspace OOMFight with Metaspace OOM
Fight with Metaspace OOM
 
Racing The Web - Hackfest 2016
Racing The Web - Hackfest 2016Racing The Web - Hackfest 2016
Racing The Web - Hackfest 2016
 
Anatomy of in memory processing in Spark
Anatomy of in memory processing in SparkAnatomy of in memory processing in Spark
Anatomy of in memory processing in Spark
 
2016-01-16 03 Денис Нелюбин. How to test a million
2016-01-16 03 Денис Нелюбин. How to test a million2016-01-16 03 Денис Нелюбин. How to test a million
2016-01-16 03 Денис Нелюбин. How to test a million
 
Audit your reactive applications
Audit your reactive applicationsAudit your reactive applications
Audit your reactive applications
 
JVM Performance Tuning
JVM Performance TuningJVM Performance Tuning
JVM Performance Tuning
 
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
 
Diagnosing HotSpot JVM Memory Leaks with JFR and JMC
Diagnosing HotSpot JVM Memory Leaks with JFR and JMCDiagnosing HotSpot JVM Memory Leaks with JFR and JMC
Diagnosing HotSpot JVM Memory Leaks with JFR and JMC
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Software Profiling: Java Performance, Profiling and Flamegraphs
Software Profiling: Java Performance, Profiling and FlamegraphsSoftware Profiling: Java Performance, Profiling and Flamegraphs
Software Profiling: Java Performance, Profiling and Flamegraphs
 
Managing Terraform Module Versioning and Dependencies
Managing Terraform Module Versioning and Dependencies Managing Terraform Module Versioning and Dependencies
Managing Terraform Module Versioning and Dependencies
 
Deployments with rails
Deployments with railsDeployments with rails
Deployments with rails
 

Plus de Misha Kozik (7)

QBIC
QBICQBIC
QBIC
 
DSL in Clojure
DSL in ClojureDSL in Clojure
DSL in Clojure
 
Writing DSL in Clojure
Writing DSL in ClojureWriting DSL in Clojure
Writing DSL in Clojure
 
Sentiments Improvement
Sentiments ImprovementSentiments Improvement
Sentiments Improvement
 
Timezone Mess
Timezone MessTimezone Mess
Timezone Mess
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in Java
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 

Dernier

Dernier (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 

Unsafe Java