🐝
Mess around software system design
  • README
  • ArchitectureTradeOffAnalysis
    • Estimation
    • Middleware
    • Network
    • Server
    • Storage
  • Conversion cheat sheet
  • Scenarios
    • TinyURL
      • Estimation
      • Flowchart
      • Shortening mechanisms
      • Rest API
      • Performance
      • Storage
      • Follow-up
    • TaskScheduler
      • JDK delay queue
      • Timer based
      • RabbitMQ based
      • Kafka-based fixed delay time
      • Redis-based customized delay time
      • MySQL-based customized delay time
      • Timer TimingWheel
      • Industrial Scheduler
      • Workflow Engine
      • Airflow Arch
    • GoogleDrive
      • Estimation
      • Flowchart
      • Storage
      • Follow-up
    • Youtube
      • Estimation
      • Flowchart
      • Performance
      • Storage
      • Follow-up
      • Netflix
    • Uber
      • Estimation
      • Rest api
      • Flowchart
      • KNN algorithms
      • Geohash-based KNN mechanism
      • Redis implementation
      • Storage
    • Twitter
      • Estimation
      • Flowchart
      • Storage
      • Scalability
      • Follow-up
    • Instant messenger
      • Architecture overview
      • Presence
      • Unread count
      • Notifications
      • Read receipt
      • Large group chat
      • Storage-Offline 1:1 Chat
      • Storage-Offline group chat
      • Storage-Message roaming
      • NonFunc-Realtime
      • NonFunc-Reliability
      • NonFunc-Ordering
      • NonFunc-Security
      • Livecast-LinkedIn
    • Distributed Lock
      • Single machine
      • AP model based
      • CP model based
      • Chubby-TODO
    • Payment system
      • Resilience
      • Consistency
      • Flash sale
    • Key value store
      • Master-slave KV
      • Peer-to-peer KV
      • Distributed cache
  • Time series scenarios
    • Observability
      • TimeSeries data
      • Distributed traces
      • Logs
      • Metrics
      • NonFunc requirments
  • Search engine
    • Typeahead
    • Search engine
    • Distributed crawler
      • Estimation
      • Flowchart
      • Efficiency
      • Robustness
      • Performance
      • Storage
      • Standalone implementation
      • Python Scrapy framework
    • Stream search
  • Big data
    • GFS/HDFS
      • Data flow
      • High availability
      • Consistency
    • Map reduce
    • Big table/Hbase
    • Haystack
    • TopK
    • Stateful stream
    • Lambda architecture
    • storm架构
    • Beam架构
    • Comparing stream frameworks
    • Instagram-[TODO]
  • MicroSvcs
    • Service Registry
      • Flowchart
      • Data model
      • High availability
      • Comparison
      • Implementation
    • Service governance
      • Load balancing
      • Circuit breaker
      • Bulkhead
      • Downgrade
      • Timeout
      • API gateway
      • RateLimiter
        • Config
        • Algorithm comparison
        • Sliding window
        • Industrial impl
    • MicroSvcs_ConfigCenter-[TODO]
    • MicroSvcs_Security
      • Authentication
      • Authorization
      • Privacy
  • Cache
    • Typical topics
      • Expiration algorithm
      • Access patterns
      • Cache penetration
      • Big key
      • Hot key
      • Distributed lock
      • Data consistency
      • High availability
    • Cache_Redis
      • Data structure
      • ACID
      • Performance
      • Availability
      • Cluster
      • Applications
    • Cache_Memcached
  • Message queue
    • Overview
    • Kafka
      • Ordering
      • At least once
      • Message backlog
      • Consumer idempotency
      • High performance
      • Internal leader election
    • MySQL-based msg queue
    • Other msg queues
      • ActiveMQ-TODO
      • RabbitMQ-TODO
      • RocketMQ-TODO
      • Comparison between MQ
  • Traditional DB
    • Index data structure
    • Index categories
    • Lock
    • MVCC
    • Redo & Undo logs
    • Binlog
    • Schema design
    • DB optimization
    • Distributed transactions
    • High availability
    • Scalability
    • DB migration
    • Partition
    • Sharding
      • Sharding strategies
      • Sharding ID generator overview
        • Auto-increment key
        • UUID
        • Snowflake
        • Implement example
      • Cross-shard pagination queries
      • Non-shard key queries
      • Capacity planning
  • Non-Traditional DB
    • NoSQL overview
    • Rum guess
    • Data structure
    • MySQL based key value
    • KeyValueStore
    • ObjectStore
    • ElasticSearch
    • TableStore-[TODO]
    • Time series DB
    • DistributedAcidDatabase-[TODO]
  • Java basics
    • IO
    • Exception handling
  • Java concurrency
    • Overview
      • Synchronized
      • Reentrant lock
      • Concurrent collections
      • CAS
      • Others
    • Codes
      • ThreadLocal
      • ThreadPool
      • ThreadLifeCycle
      • SingletonPattern
      • Future
      • BlockingQueue
      • Counter
      • ConcurrentHashmap
      • DelayedQueue
  • Java JVM
    • Overview
    • Dynamic proxy
    • Class loading
    • Garbage collection
    • Visibility
  • Server
    • Nginx-[TODO]
  • Distributed system theories
    • Elementary school with CAP
    • Consistency
      • Eventual with Gossip
      • Strong with Raft
      • Tunable with Quorum
      • Fault tolerant with BFT-TODO
      • AutoMerge with CRDT
    • Time in distributed system
      • Logical time
      • Physical time
    • DDIA_Studying-[TODO]
  • Protocols
    • ApiDesign
      • REST
      • RPC
    • Websockets
    • Serialization
      • Thrift
      • Avro
    • HTTP
    • HTTPS
    • Netty-TODO
  • Statistical data structure
    • BloomFilter
    • HyperLoglog
    • CountMinSketch
  • DevOps
    • Container_Docker
    • Container_Kubernetes-[TODO]
  • Network components
    • CDN
    • DNS
    • Load balancer
    • Reverse proxy
    • 云中网络-TODO
  • Templates
    • interviewRecord
  • TODO
    • RecommendationSystem-[TODO]
    • SessionServer-[TODO]
    • Disk
    • Unix philosophy and Kafka
    • Bitcoin
    • Design pattern
      • StateMachine
      • Factory
    • Akka
    • GoogleDoc
      • CRDT
Powered by GitBook
On this page

Was this helpful?

  1. Java concurrency
  2. Codes

ThreadLifeCycle

PreviousThreadPoolNextSingletonPattern

Last updated 1 year ago

Was this helpful?

Thread Lifecycle

State conversion

  • When will be a thread blocked?

    • Blocked:

    • Waiting:

    • Timed waiting:

  • New -> Runnable -> terminated is not reversible

  • Timed waiting / Waiting / Blocked can only transfer to each other by going through Runnable first.

Create thread - implementing Runnable vs extending Thread

  • Internal mechanism

    • There is only one way to create thread - create a Thread instance. And there are two ways to implement the run() method - Override the run() method inside Thread instance vs pass an implementation of Runnable interface into Thread constructor.

    • Thread and Runnable are complement to each other for multithreading not competitor or replacement. Because we need both of them for multi-threading.

      • For Multi-threading we need two things:

        • Something that can run inside a Thread (Runnable).

        • Something That can start a new Thread (Thread).

      • So technically and theoretically both of them is necessary to start a thread, one will run and one will make it run (Like Wheel and Engine of motor vehicle).

@Override
public void run() 
{
    if (target != null) 
    {
        target.run();
    }
}
  • Best practices - Implement Runnable()

    • Code cleaniness perspective:

      • Decoupling: Implementing Runnable could separate thread creation from running.

      • Extensibility: If adopting the approach of extending Thread, then it could not extend another class because Java does not support multiple inheritance.

    • Cost of operation perspective: Thread approach will require creating and destroying a thread object each time; When combined with threadpool, Runnable approach could avoid creating a new thread object and deleting it.

// Approach 1: Runnable
public class DemoRunnable implements Runnable 
{
    public void run() 
    {
        //Code
    }
}

// Approach 2: Thread
public class DemoThread extends Thread 
{
    public DemoThread() 
    {
        super("DemoThread");
    }

    public DemoThread(Runnable ) 
    {
        super("DemoThread");
    }

    public void run() 
    {
        //Code
    }
}

Start a thread

  • Best practices - Use Start()

    • Start() method responsiblity:

      • Start a new thread

      • Check the thread status

      • Add the thread to thread group

      • Kick off the Run()

    • Run() method responsibility:

      • Kick off the code inside Run()

    • Key difference is that Start() method (approach 1 below) will create a new thread to run. Run() (approach 2 below) will run everything inside main() method.

public static void main(string[] args)
{
    // Approach 1: Create a runnable instance and run it
    // Output: main
    Runnable runnable = () -> 
    {
        System.out.println(Thread.currentThread().GetName());
    };
    runnable.run();

    // Approach 2: Start a new thread
    // Output: thread0
    new Thread(runnable).start();
}

Stop a thread

  • Java does not provide a way for one thread to force stop of another thread because if it does so, then the other thread might be in a state of inconsistency. Java provides a collaboration mechanism for one thread to notify another thread that it would better stop.

Object methods

Wait, notify and notifyAll

  • Wait and notify are all based on object's monitor mechanism. Therefore, they are declared as methods on top of Object.

  • They are considered the native way of doing multi-threading. Java JDK has shipped packages such as Condition variable which is easier to use.

Thread methods

Join

  • Join thread will be in the waiting status

  • Join is the native way of doing waiting. Java JDK has shipped packages such as CountDownLatch or CyclicBarrier.

  • Best pratices:

Sleep

  • Wait vs Sleep

    • Similarities:

      • Both wait and sleep method could make the thread come into blocked state. Wait will result in Waiting and sleep will result in Time_Waiting.

      • Both wait and sleep method could respond to interrupt.

    • Differences:

      • Wait could only be used in synchronized blocks, while sleep could be used in other scenarios.

      • Wait is a method on Object, and sleep is a method on Thread.

      • Wait will release monitor lock, and sleep will not.

      • Wait could only exit blocked state reactively, and sleep could proactive exit after specific time.

  • Yield vs Sleep: Similar. However yield is non-blocking but sleep is blocking

Best practices: Please see this folder for sample code:

Please see for best practices

Please see

Thread Lifecycle
State conversion
Create thread - implementing Runnable vs extending Thread
Start a thread
Stop a thread
Object methods
Wait, notify and notifyAll
Thread methods
Join
Sleep
https://github.com/DreamOfTheRedChamber/system-design-interviews/tree/master/code/multithreads/StopThreads
https://github.com/DreamOfTheRedChamber/system-design-interviews/tree/master/code/multithreads/ObjectMethods
https://github.com/DreamOfTheRedChamber/system-design-interviews/tree/master/code/multithreads/ThreadMethods