Introduction to Java threads-sharing access to data

Source: Internet
Author: User
Tags visibility volatile

Shared variables

To make multiple threads useful in a program, they must have some way to communicate with each other or share their results.

The easiest way to let threads share their results is to use shared variables. They should also use synchronization to ensure that values propagate correctly from one thread to another, and to prevent another thread from seeing inconsistent intermediate results when one thread is updating some related data items.

The example of calculating prime numbers in the thread base uses a shared Boolean variable that indicates that the specified time period has passed. This illustrates the simplest form of sharing data between threads: polling a shared variable to see if another thread has finished performing a task.

All threads that exist in the same memory space

As discussed earlier, threads and processes have a lot in common, unlike threads that share the same process context, including memory, with other threads in the same process. This is very convenient, but it also has a major responsibility. Threads can easily exchange data with each other as long as they access shared variables (static or instance fields), but threads must also ensure that they access shared variables in a controlled manner lest they interfere with each other's changes.

Any thread can access all variables within its scope, just as the main thread can access the variable. The prime number example uses a common instance field, called finished, to indicate that a specified time has elapsed. When the timer expires, a thread writes the field, and another thread periodically reads the field to check if it should stop. Note: This field is declared as volatile, which is important for the proper operation of this program. In the back of this chapter, we'll see why.

Synchronization of controlled access

To ensure that data can be shared between threads in a controlled manner, the Java language provides two keywords: synchronized and volatile.

Synchronized has two important meanings: it ensures that only one thread at a time can execute a protected part of the code (mutual exclusion, mutual exclusion, or mutex), and it ensures that the data changed by one thread is visible to other threads (change visibility).

Without synchronization, the data can easily be in an inconsistent state. For example, if a thread is updating two related values (for example, the position and rate of the particle, while another thread is reading the two values, it is possible to schedule the second thread to run when the first thread has written only one value and not another, so that it sees an old value and a new value. Synchronization allows us to define blocks of code that must be run atomically so that, for other threads, they are either executed or not executed.

Synchronous atomic execution or mutually exclusive aspects are similar to the concepts of critical segments in other operating environments.

Ensure the visibility of shared data changes

Synchronization allows us to ensure that threads see a consistent view of memory.

The processor can use caching to speed up access to memory (or the compiler can store values in registers for faster access). On some multiprocessor architectures, if you modify the memory location in a processor's cache, there is no need for other processors to see this modification until the writer's cache is refreshed and the reader's cache is invalidated.

This means that on such a system, two threads executing on two different processors may see two different values for the same variable! It sounds scary, but it's very common. It simply means that certain rules must be followed when accessing data that is used or modified by other threads.

Volatile is simpler than synchronization and is only suitable for controlling access to a single instance of a basic variable (integers, boolean variables, and so on). When a variable is declared as volatile, any write operation on the variable bypasses the cache, writes the master memory directly, and any read of the variable bypasses the cache and takes its own memory directly. This means that all threads will see the same volatile variable values at any time.

If there is no correct synchronization, the thread may see the old variable value or cause other forms of data corruption.

Block of atomic code protected with locks

Volatile is useful for ensuring that each thread sees the latest variable value, but sometimes we need to protect larger pieces of code, such as fragments that involve updating multiple variables.

Synchronization uses the concept of monitor or lock to coordinate access to specific blocks of code.

Each Java object has an associated lock. Only one thread at a time can hold a Java lock. When a thread enters a synchronized code block, the thread blocks and waits until the lock is available, and when it is available, it gets the lock and executes the code block. When control exits a protected code block, it releases the lock when it reaches the end of the code block or throws an exception that is not caught in the synchronized block.

This way, only one thread at a time can execute a block of code protected by the given monitor. From the point of view of other threads, the code block can be thought of as an atom, which either executes all or does not execute at all.

Related Article

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.