Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What does thread safety mean?

Shulou Source: shulou.com Published: 2022-06-02 08:27:57 10月14日 Update

This article introduces the relevant knowledge of "what is the meaning of thread safety". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Https://blog.csdn.net/suifeng3051/article/details/52164267

Personal summary:

Thread safety: atomicity, visibility, orderliness

Thread safety can be simply understood as

A method or an instance can be used in a multithreaded environment without problems

Multiple threads accessed the same resource

Same memory area (variable, array, or object), system (database, web services, etc.) or file, etc.

Occurs only when one or more threads write to these resources

As long as the resource does not change, it is safe for multiple threads to read the same resource.

We don't know when the operating system will switch between two threads.

Order will be broken.

Local variables of the underlying type are thread-safe

Local variables defined inside the method

Local object references are not necessarily, because objects exist in the heap, and there can be multiple references to determine whether the resource object is thread-safe.

For example, multi-threads create database connections separately, which is thread-safe at the connection level.

But manipulating the same data in the database is not thread-safe at the database level.

Even if an object is thread-safe and immutable, a reference to that object may not be thread-safe

For example, ConcurrentHashMap is thread-safe, but using it get, set is not thread-safe.

The method of realizing thread safety in Java

In Java multithreaded programming, there are several ways to achieve Java thread safety:

The easiest way to use the Synchronization keyword: Java Synchronization introduction

Use atomic classes in the java.util.concurrent.atomic package, such as AtomicInteger

Use locks in the java.util.concurrent.locks package

Use the thread-safe collection ConcurrentHashMap

Use the volatile keyword to ensure variable visibility (read directly from memory, not from thread cache)

That's all for "what does thread safety mean?" Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Thread security object data resource variable multiple same local database method meaning order keyword keyword memory content atom level way Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Docker MariaDB Shulou Information NVidia