Java Concurrency Model (i)

Source: Internet
Author: User

Learning materials from http://ifeve.com/java-concurrency-thread-directory/

One, multi-threaded

    1. the difference between a process and a thread: A program runs at least one process, and a process contains at least one thread.
    2. Multithreading: Multithreading enables multiple threads to execute in parallel within a program, and a thread's execution can be thought of as a CPU executing the program, when a program runs under multiple threads, as if there is more than one CPU executing the program at the same time.

Multithreading executes concurrently within the same program, so concurrent read and write operations are performed on the same memory space.

Thinking:

    1. If a thread is reading one memory and another thread is writing to that memory, what will the thread that reads the operation get? is the old value before the write operation? Or the new value after the write operation is successful? or half the value of a new scuffed?
    2. If two threads write a memory, what happens after the operation is completed? is the value written by the first thread? Or the value that the second thread writes? Or is it a mixed value that two threads write together?

Second, the advantages of multithreading

1. Better utilization of resources

For example, the CPU is waiting for the disk to read the time is very idle, can use this time to do some other things.

2 , programming is simpler in some cases

For example, single-threaded to operate two files read and processing, you need to record the read and processing status of each file. Conversely, if you use two threads to process one file, one thread will block the other when it is read, and the blocked thread will be able to perform the processing. Not only improves disk and CPU utilization, but also makes programming easier.

3 , faster program response

For example, the server listens for incoming requests on a certain port, when a request arrives, it handles the request, and then returns to listen for other requests when it has finished processing. Suppose this request takes a lot of time?

Another way is that the server listener thread passes the incoming request to the worker thread and then immediately returns to the listener so that it can accept and handle requests sent by more clients, and the service responds faster.

Third, the cost of multithreading

1 , more complex design

In general, multithreaded applications are more complex than single-threaded applications, where the interaction between threads is often very complex when multithreaded access to shared data, and incorrect thread synchronization produces errors that are very difficult to discover and reproduce to fix.

2 , the cost of context switching

When the CPU performs a thread switch to execute another thread, it needs to store the current thread's local data, the program pointer, etc., and then load the local data of the other thread, the program pointer, and so on, before it starts executing. This switch is called context Switch, where the CPU executes one thread in one context and switches to another (context) to execute another thread.

If there is no need, you should minimize context switching.

3 , increase resource consumption

In addition to the CPU, the thread also needs some memory to maintain its local stack, and it needs to occupy some resources in the operating system to manage the threads. We can write a program to create 100 threads, and then these threads just wait for nothing to do and then see how much memory is being consumed.

Iv. Concurrent Programming model

The concurrent programming model specifies how multiple threads in a system can collaborate to complete the jobs assigned to them, and different concurrency models split the jobs in different ways, while the collaboration and interaction between threads is not the same.

1. the similarity between concurrency model and distributed system

Concurrency modeling is similar to many of the architectures used in distributed systems, where processes can be

Communication (processes may be in different machines) and can also communicate with each other in the middle of a concurrent system. For example, the model for assigning jobs to workers (threads) is generally similar to the load balancing system in distributed systems.

2. Parallel worker

The delegate assigns the incoming job to a different worker, each worker completes the task, and the worker works on a different thread, possibly even on a different CPU.

Pros: easy to understand, only need to add more workers to improve the degree of parallelism of the system.

Disadvantages:

    1. Concurrent workers often need to access some shared data, both in memory and in the database, which can become complex once a shared state is involved. A thread needs to access the shared data in some way to ensure that a thread's modifications are visible to other threads. Threads need to avoid the concurrency problems of the state, deadlock, and many other shared states.

While waiting for access to shared data, waiting between threads loses some parallelism, and many concurrent data structures are blocked, meaning that only one or a few threads can access at some point, resulting in a competitive state of shared data and a certain serialization.

    1. Stateless worker sharing states can be modified by other threads, so workers must reread the state every time they need to make sure that the latest copy is accessible every time. Workers cannot save this state internally, which is called Stateless. In particular, when the state is stored in an external database, each repetition can cause slower speed.
    2. The task order is indeterminate: Job A may have been assigned to workers before job B, but job B might have been executed before job a, which means that there is no guarantee that the job will be executed first or last.

3. Pipeline Model

Also known as reactor systems, event-driven systems, or no shared models.

Similar to the workers on the factory line, each worker is responsible for only part of the job, and when the work is done, it is forwarded to the next worker, each worker running in his own thread and not sharing state with other workers.

In practice, there may be a number of different virtual pipeline simultaneous actions, the reality may be such a situation.

Actors and channels

Each worker in the actors model is called actor. The actor can send and process messages directly and asynchronously, and the actor can be used to implement one or more of the kind of job-processing pipeline described earlier.

In the channel model, the work is not communicated directly to each other. Back, they publish their own messages (events) in different channels. Other workers can listen to messages on these channels, and the sender does not need to know who is listening.

Advantages of pipelining Models:

    1. No need to share a state
    2. Workers with status
    3. Better Hardware Integration
    4. Reasonable Order of operations

Disadvantages of pipelining Models:

    1. Job executions are often distributed across multiple workers and are therefore distributed across multiple classes in a project. This makes it difficult to track exactly what code is being executed by a job.
    2. The difficulty of writing code is increased, and sometimes the worker's code needs to be written in the form of callback processing. If too many callback handlers are embedded in the code, the so-called Callback Inferno (callback Hell) is often present.

4. Function-type execution (functional Parallelism)

The basic idea of functional parallelism is to implement programs using function calls, which are considered agents (agents) or actors, and functions can send messages to each other like pipelining models (aka reactors or event-driven systems).

think: What kind of concurrency model to use?

Usually, the answer depends on what your system intends to do. If your job itself is parallel, independent, and not necessarily shared, you might use a parallel worker model to implement your system.

Many jobs are not natural parallel and independent, for this type of system, the use of pipeline concurrency model can better play its advantages, and more than the parallel worker model more advantages.

Java Concurrency Model (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.