SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

Andere mochten auch (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
 

Ähnlich wie ぐだ生 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
 

Ähnlich wie ぐだ生 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Nikki Chapple
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 

Kürzlich hochgeladen (20)

Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 

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

Hinweis der Redaktion

  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