SlideShare a Scribd company logo
1 of 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();
    rl.lock();
} 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

More Related Content

What's hot

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
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CPavel Albitsky
 
Full solution to bounded buffer
Full solution to bounded bufferFull solution to bounded buffer
Full solution to bounded bufferSyed Zaid Irshad
 
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
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCanSecWest
 
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
 
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
 

What's hot (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
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-C
 
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
 
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
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemes
 
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
 
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
 

Similar to ぐだ生 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
 
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
 
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
 
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
 

Similar to ぐだ生 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
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming Languages
 
Thread
ThreadThread
Thread
 
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
 
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...
 
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?
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Chapter v(error)
Chapter v(error)Chapter v(error)
Chapter v(error)
 
Play image
Play imagePlay image
Play image
 
Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02
 

More from 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
 

More from 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
 

Recently uploaded

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
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
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
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
 
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 textsMaria Levchenko
 
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 WorkerThousandEyes
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
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
 
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
 

Recently uploaded (20)

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
 
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
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
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
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
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
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
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...
 
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
 

ぐだ生 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(); rl.lock(); } 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

Editor's Notes

  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