What issues should I pay attention to when writing multi-threaded Java programs? (From objective Java SE)

Source: Internet
Author: User

Multi-threaded programming may cause many problems, and sometimes the problems cannot be reproduced, or you may not know when to reproduce them. Or the test is passed, but a problem occurs during the actual operation. Or there are different virtual machines and compilers.

Performance. This is also a common interview question. This question is very big and involves many aspects. Let's talk about some of my experiences below:

1) The more threads, the better.

Multithreading is used for a network service to face a large number of client requests at the same time, or to request a large number of addresses at the same time, such as web crawlers.

B. graphic interface programming involving GUI can improve the response speed

C makes full use of the features of multi-core CPU to improve the efficiency of program execution.

It usually takes dozens to dozens, and the specific situation is analyzed.

2) correctly synchronize and access the shared variable data

Two Functions of synchronized synchronization: access a serializes, so that the variable object remains in a consistent state when being observed by the outside world. Otherwise, the object cannot be accessed (mutual exclusion)

B. make the modifications made by one thread visible to other threads (Communication Effects)

All basic types except long and double, or the reading and writing of object references are atomic. This ensures a, but B is not guaranteed, so the volatile keyword is required.

(The volatile modifier performs no mutual exclusion, it

Guarantees that any thread that reads the field will see the most recently written value)

 

The auto-increment operation is not atomic. The increment operator (++) is not Atomic

 

You can share unchanged objects without such problems. (Effectively immutable, Safe publication)

 

To sum up, when some threads share variable data, the data read and write methods of each thread must be displayed using synchronization.

In summary, when multiple threads share mutable data, each thread that

Reads or writes the data must perform synchronization

3) avoid excessive Synchronization

Excessive synchronization may cause performance degradation, deadlocks, and even non-deterministic behaviors (Nondeterministic behavior .)

(A) To avoid liveness and safety failures, never cede control to the client within a synchronized method or block

In other words, do not call the method designed as override or the function object provided by the client in the synchronization area.

(B) do as little as possible in the synchronization method as a rule, you shoshould do as little work as possible inside synchronized regions.

If a variable class is used for multi-threaded shared access, you should keep it thread safe. Because internal synchronization is much more efficient than locking the entire object.

(You shoshould make a mutable class thread-safe (item 70) if it is intended

Concurrent Use and you can achieve significantly higher concurrency by synchro-

Nizing internally than you cocould by locking the entire object externally)

If this is not the case, you should not use synchronization. Just like stringbuffer, it is now replaced by stringbuilder

In summary, to avoid deadlock and data upload uption, never call an alien Method

From within a synchronized region. More generally, try to limit the amount

Work that you do from within synchronized regions. When you are designing

Mutable class, think about whether it shoshould do its own synchronization. In

Modern multicore era, it is more important than ever not to synchronize exces-

Sively. Synchronize your class internally only if there is a good reason to do so,

And document your demo-clearly

4) prefer executors and tasks to threads

 

Executorservice executor = executors. newsinglethreadexecutor ();

Executor.exe cute (runnable );

Executor. Shutdown ();

 

The factory method of Java. util. Concurrent. executors provides the executor you need in most cases. If you want to customize one, you can directly use threadpoolexecutor.

 

Scheduledthreadpoolexecutor

 

In essence, the executor framework does for execution what the collections framework did for aggregation.

5) prefer concurrency utilities to wait and Policy

6) use lazy initialization judiciously

7) Don't depend on the thread Scheduler

8) Avoid thread groups

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.