SlideShare une entreprise Scribd logo
1  sur  31
Java
Thread

           2011 4    9
         twitter: @zaki50
Who am I

•          YAMAZAKI Makoto(twitter: @zaki50)
•   Android

    •
    •   StickyShortcut
•           Java
• Effective Java       2

  • ISBN:978-4-89471-499-1

  • 3,780   (      )

  •      66,       69
Agenda


• synchronized / volatile
• Lock(ReentrantLock)
• java.util.concurrent
synchronized
Eclipse   (jvisualvm)
synchronized
class Sample {
    public synchronized void execute1() {
        //
    }
    public void execute1b() {
        synchronized (this) {
            //
        }
    }
    public static synchronized void execute2() {
        //
    }
    public static synchronized void execute2b() {
        synchronized (Sample.class) {
            //
        }
    }
}
synchronized

•

•

•
•
•
         (by Wikipedia)

• Java       1
    1


                 1
                     1
•

    • synchronized

    • Object#wait()

•

    • synchronized

    • Object#wait()
•
    synchronized



•
synchronized
class Sample {
    public synchronized void execute1() {
        //
    }
    public void execute1b() {
        synchronized (this) {
            //
        }
    }
    public static synchronized void execute2() {
        //
    }
    public static synchronized void execute2b() {
        synchronized (Sample.class) {
            //
        }
    }
}
•
•
• Java VM



    •

    •

•
private static boolean stopRequested = false;
private static int value = 0;

public static void main(String[] args) throws Exception {
    new Thread() {
        @Override
        public void run() {
            int i = 0;
                                                 if (!stopRequested) {
            while (!stopRequested) {                 while (true) {
                i++;                                     i++;
            }
                                                     }
                                                 }
            System.out.println(value);
        }
    }.start();

    TimeUnit.SECONDS.sleep(1L);
    value = 100;
    stopRequested = true;
}
private static boolean stopRequested = false;
private static int value = 0;

public static void main(String[] args) throws Exception {
    new Thread() {
        @Override
        public void run() {
            int i = 0;
            while (!stopped()) {
                i++;
            }
            System.out.println(value);
        }
    }.start();                   private synchronized static void stop() {
                                     stopRequested = true;
    TimeUnit.SECONDS.sleep(1L); }
    value = 100;
    stop();                      private synchronized static boolean stopped() {
}                                    return stopRequested;
                                 }
volatile
volatile

•

• volatile



• volatile
volatile
private volatile static boolean stopRequested = false;
private volatile static int value = 0;

public static void main(String[] args) throws Exception {
    new Thread() {
        @Override
        public void run() {
            int i = 0;

            while (!stopRequested) {
                i++;
            }

            System.out.println(value);
        }
    }.start();

    TimeUnit.SECONDS.sleep(1L);
    value = 100;
    stopRequested = true;
}
Lock
Lock
• synchronized



 • lock() // synchronized

 • tryLock() //

 • tryLock(long,TimeUnit) //

 • lockInterruptibly() //
•

    •           try - finally
        Lock l = ...;
        l.lock();
        try {
            //
        } finally {
            l.unlock();
        }
ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

Lock wl = rwLock.writeLock();
Lock rl;
wl.lock();
try {
    // write


    rl = rwLock.readLock();
} finally {
    wl.unlock();
}
try {
    // read
} finally {
    rl.unlock();
}
Lock
• lock()     synchronized



• unlock()     synchronized



•                Lock
java.util.concurrent
...

• wait()   notify()/notifyAll()
                                  (    )

•
java.util.concurrent
•
    Javadoc of java.util.concurrent
    • ExecutorService
    •

    •

    •

    • ConcurrentCollections
    •
• synchronized

• Java           17.4 Memory Model

•                       java.util.concurrent



•     Java

    • Doug Lea    ISBN:4-7973-3720-6

Contenu connexe

Tendances

Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerabilityCsw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerabilityCanSecWest
 
Full solution to bounded buffer
Full solution to bounded bufferFull solution to bounded buffer
Full solution to bounded bufferSyed Zaid Irshad
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CPavel Albitsky
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM ProfilingAndrei Pangin
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Alexey Fyodorov
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languagesRafael Winterhalter
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCanSecWest
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
 

Tendances (19)

Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerabilityCsw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
 
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
 
Full solution to bounded buffer
Full solution to bounded bufferFull solution to bounded buffer
Full solution to bounded buffer
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-C
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM Profiling
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
 
C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemes
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 

En vedette

En vedette (6)

076-600.pdf
076-600.pdf076-600.pdf
076-600.pdf
 
Flisol Uni 2009
Flisol Uni 2009Flisol Uni 2009
Flisol Uni 2009
 
Successful Citizen Service - This Road's Built for You
Successful Citizen Service - This Road's Built for YouSuccessful Citizen Service - This Road's Built for You
Successful Citizen Service - This Road's Built for You
 
for Perl newbie
for Perl newbiefor Perl newbie
for Perl newbie
 
孩子你慢慢来
孩子你慢慢来孩子你慢慢来
孩子你慢慢来
 
Promoting best practice for early warning of landslides - Reclaim 3
Promoting best practice for early warning of landslides - Reclaim 3Promoting best practice for early warning of landslides - Reclaim 3
Promoting best practice for early warning of landslides - Reclaim 3
 

Similaire à ぐだ生 Java入門第ニ回(synchronized and lock)

Java synchronizers
Java synchronizersJava synchronizers
Java synchronizersts_v_murthy
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with nettyZauber
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency beginingmaksym220889
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming LanguagesYudong Li
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormDavorin Vukelic
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Artur Latoszewski
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Víctor Bolinches
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join frameworkMinh Tran
 
Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Tarun Kumar
 

Similaire à ぐだ生 Java入門第ニ回(synchronized and lock) (20)

Java synchronizers
Java synchronizersJava synchronizers
Java synchronizers
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
Concurrency gotchas
Concurrency gotchasConcurrency gotchas
Concurrency gotchas
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Thread
ThreadThread
Thread
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming Languages
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache Storm
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Chapter v(error)
Chapter v(error)Chapter v(error)
Chapter v(error)
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02
 
Play image
Play imagePlay image
Play image
 

Plus de Makoto Yamazaki

20150425 DroidKaigi つかえるGradleプロジェクトの作り方
20150425 DroidKaigi つかえるGradleプロジェクトの作り方20150425 DroidKaigi つかえるGradleプロジェクトの作り方
20150425 DroidKaigi つかえるGradleプロジェクトの作り方Makoto Yamazaki
 
Custom lintcheckをつくろう
Custom lintcheckをつくろうCustom lintcheckをつくろう
Custom lintcheckをつくろうMakoto Yamazaki
 
20120516 第7回ウフィカ社内ハンズオン Git基礎
20120516 第7回ウフィカ社内ハンズオン Git基礎20120516 第7回ウフィカ社内ハンズオン Git基礎
20120516 第7回ウフィカ社内ハンズオン Git基礎Makoto Yamazaki
 
ICS ホットトピック
ICS ホットトピックICS ホットトピック
ICS ホットトピックMakoto Yamazaki
 
DevQuiz 2011 の模範解答 Android編
DevQuiz 2011 の模範解答 Android編DevQuiz 2011 の模範解答 Android編
DevQuiz 2011 の模範解答 Android編Makoto Yamazaki
 
USB Host APIで遊んでみた
USB Host APIで遊んでみたUSB Host APIで遊んでみた
USB Host APIで遊んでみたMakoto Yamazaki
 
20110619 live view ideathon_logcatonliveview
20110619 live view ideathon_logcatonliveview20110619 live view ideathon_logcatonliveview
20110619 live view ideathon_logcatonliveviewMakoto Yamazaki
 
I/O 2011 報告会 ADKで遊んでみた
I/O 2011 報告会 ADKで遊んでみたI/O 2011 報告会 ADKで遊んでみた
I/O 2011 報告会 ADKで遊んでみたMakoto Yamazaki
 
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)ぐだ生 Java入門第三回(文字コードの話)(Keynote版)
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)Makoto Yamazaki
 
ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)Makoto Yamazaki
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)Makoto Yamazaki
 
20110326 ネットプリントの紹介
20110326 ネットプリントの紹介20110326 ネットプリントの紹介
20110326 ネットプリントの紹介Makoto Yamazaki
 
20110109 abc2010w gingerbread_api_storage
20110109 abc2010w gingerbread_api_storage20110109 abc2010w gingerbread_api_storage
20110109 abc2010w gingerbread_api_storageMakoto Yamazaki
 

Plus de Makoto Yamazaki (13)

20150425 DroidKaigi つかえるGradleプロジェクトの作り方
20150425 DroidKaigi つかえるGradleプロジェクトの作り方20150425 DroidKaigi つかえるGradleプロジェクトの作り方
20150425 DroidKaigi つかえるGradleプロジェクトの作り方
 
Custom lintcheckをつくろう
Custom lintcheckをつくろうCustom lintcheckをつくろう
Custom lintcheckをつくろう
 
20120516 第7回ウフィカ社内ハンズオン Git基礎
20120516 第7回ウフィカ社内ハンズオン Git基礎20120516 第7回ウフィカ社内ハンズオン Git基礎
20120516 第7回ウフィカ社内ハンズオン Git基礎
 
ICS ホットトピック
ICS ホットトピックICS ホットトピック
ICS ホットトピック
 
DevQuiz 2011 の模範解答 Android編
DevQuiz 2011 の模範解答 Android編DevQuiz 2011 の模範解答 Android編
DevQuiz 2011 の模範解答 Android編
 
USB Host APIで遊んでみた
USB Host APIで遊んでみたUSB Host APIで遊んでみた
USB Host APIで遊んでみた
 
20110619 live view ideathon_logcatonliveview
20110619 live view ideathon_logcatonliveview20110619 live view ideathon_logcatonliveview
20110619 live view ideathon_logcatonliveview
 
I/O 2011 報告会 ADKで遊んでみた
I/O 2011 報告会 ADKで遊んでみたI/O 2011 報告会 ADKで遊んでみた
I/O 2011 報告会 ADKで遊んでみた
 
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)ぐだ生 Java入門第三回(文字コードの話)(Keynote版)
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)
 
ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)
 
20110326 ネットプリントの紹介
20110326 ネットプリントの紹介20110326 ネットプリントの紹介
20110326 ネットプリントの紹介
 
20110109 abc2010w gingerbread_api_storage
20110109 abc2010w gingerbread_api_storage20110109 abc2010w gingerbread_api_storage
20110109 abc2010w gingerbread_api_storage
 

Dernier

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
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 organizationRadu Cotescu
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
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 Processorsdebabhi2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

ぐだ生 Java入門第ニ回(synchronized and lock)

  • 1. Java Thread 2011 4 9 twitter: @zaki50
  • 2. Who am I • YAMAZAKI Makoto(twitter: @zaki50) • Android • • StickyShortcut • Java
  • 3. • Effective Java 2 • ISBN:978-4-89471-499-1 • 3,780 ( ) • 66, 69
  • 4. Agenda • synchronized / volatile • Lock(ReentrantLock) • java.util.concurrent
  • 6. Eclipse (jvisualvm)
  • 7. synchronized class Sample { public synchronized void execute1() { // } public void execute1b() { synchronized (this) { // } } public static synchronized void execute2() { // } public static synchronized void execute2b() { synchronized (Sample.class) { // } } }
  • 9.
  • 10.
  • 11. (by Wikipedia) • Java 1 1 1 1
  • 12. • synchronized • Object#wait() • • synchronized • Object#wait()
  • 13. synchronized •
  • 14. synchronized class Sample { public synchronized void execute1() { // } public void execute1b() { synchronized (this) { // } } public static synchronized void execute2() { // } public static synchronized void execute2b() { synchronized (Sample.class) { // } } }
  • 15.
  • 16.
  • 17. • Java VM • • •
  • 18. private static boolean stopRequested = false; private static int value = 0; public static void main(String[] args) throws Exception { new Thread() { @Override public void run() { int i = 0; if (!stopRequested) { while (!stopRequested) { while (true) { i++; i++; } } } System.out.println(value); } }.start(); TimeUnit.SECONDS.sleep(1L); value = 100; stopRequested = true; }
  • 19. private static boolean stopRequested = false; private static int value = 0; public static void main(String[] args) throws Exception { new Thread() { @Override public void run() { int i = 0; while (!stopped()) { i++; } System.out.println(value); } }.start(); private synchronized static void stop() { stopRequested = true; TimeUnit.SECONDS.sleep(1L); } value = 100; stop(); private synchronized static boolean stopped() { } return stopRequested; }
  • 22. volatile private volatile static boolean stopRequested = false; private volatile static int value = 0; public static void main(String[] args) throws Exception { new Thread() { @Override public void run() { int i = 0; while (!stopRequested) { i++; } System.out.println(value); } }.start(); TimeUnit.SECONDS.sleep(1L); value = 100; stopRequested = true; }
  • 23. Lock
  • 24. Lock • synchronized • lock() // synchronized • tryLock() // • tryLock(long,TimeUnit) // • lockInterruptibly() //
  • 25. • try - finally Lock l = ...; l.lock(); try { // } finally { l.unlock(); }
  • 26. ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); Lock wl = rwLock.writeLock(); Lock rl; wl.lock(); try { // write rl = rwLock.readLock(); } finally { wl.unlock(); } try { // read } finally { rl.unlock(); }
  • 27. Lock • lock() synchronized • unlock() synchronized • Lock
  • 29. ... • wait() notify()/notifyAll() ( ) •
  • 30. java.util.concurrent • Javadoc of java.util.concurrent • ExecutorService • • • • ConcurrentCollections •
  • 31. • synchronized • Java 17.4 Memory Model • java.util.concurrent • Java • Doug Lea ISBN:4-7973-3720-6

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n