How to write thread-safe code (JAVA)

Source: Internet
Author: User

Using multithreading can be a thread-safe issue. Many Java programmers struggle with writing multithreading, or simply understand the thread-safe code that is not. In This article, I'm not going to go into the article on thread safety, detailing the synchronization mechanism, but instead I'm just using a simple, non-thread-safe code example to lead, and then focus on understanding what is thread safety and how to make the code thread-safe.

OK, so let's take a look at a non-thread-safe code and try to find out why it's not thread safe.

/** non-thread-safe class */public class Counter {private int count, public int GetCount () {return count++; }}

You should be able to see that the above code is non-thread safe because the + + operation is not atomic, and may be problematic when reading, updating, or writing back.

For example, when multiple threads are accessing the GetCount () method at the same time, these threads may manipulate count at the same time, with some overlapping results. For example, thread 1 is updating Count,thread 2 to read count, but still gets the old value, then the last Thread 2 will overwrite the update of Thead 1, so in the concurrency environment we have to consider the atomicity of the + + operation.

In Java programming, there are many ways to write thread-safe code:

1), using the Synchronized keyword, synchonized can lock the GetCount () method, at some point only one thread can execute it, it also implements thread safety

2), using the atomic Integer, the atomic integer can guarantee the atomicity of the + + operation

Okay, let's see. Thread-safe version of Counter

public class Counter {    private int count;    Atomicinteger atomiccount = new Atomicinteg ER (0);      /**1, synchronized so thread safe */    public synchronized int GetCount () {        return count++;   }      /*     * 2, atomic growth operations, so thread safety      */    public int Getcountatomically () {        return atomiccount.incrementandget ();    }} java thread safety is an important point:  in Java programming, remember that these key points can help you avoid serious concurrency problems, such as conditional competition or deadlock. 1), immutable objects are thread-safe by default because they are not modified once they are created. For example, String is an immutable object and is thread-safe.  2), read-only, final type variables are also thread-safe  3), locks are also a thread-safe way  4)  , static variables, if not properly synchronized, can also cause thread-safety problems  5), Use thread-safe classes: Vector, Hashtable, Concurrenthashmap, String etc. 6), atomic operation is thread-safe reading A-a-bit int from memory because it S an atomic operation it can ' t interleave with OTHer thread. 7)  , local variables are also thread-safe because each thread has its own variable copy. Using local variables is a good way to keep your code thread safe. (ThreadLocal)  8), the number of shared objects between multiple threads as little as possible to avoid thread-safety issues  9)  , Volatile keyword    OK, These are all the main points about writing thread-safe classes or code and avoiding concurrency problems. To be honest, thread safety is a tricky concept, and you need to think about concurrency to see if your code is thread-safe. Of course, the JVM can also reorder the code to achieve its own tuning. However, the same code in the development environment is not necessarily guaranteed to be on-line and normal. Because the JVM will go self-tuning, reordering, and so on to optimize the code, these may also generate thread-safe issues.  



How to write thread-safe code (JAVA)

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.