Home Java javaTutorial Classes in Java collections about thread safety

Classes in Java collections about thread safety

Jan 23, 2017 pm 04:42 PM

Thread-safe classes in Java collections

Thread-safe classes

In the collection framework, some classes are thread-safe, these are all in jdk1.1 appeared. After jdk1.2, many non-thread-safe classes appeared. The following are these thread-safe synchronization classes:

vector: It has one more synchronization mechanism (thread safety) than arraylist. Because of its low efficiency, its use is no longer recommended. In web applications, especially front-end pages, efficiency (page response speed) is often a priority.

statck: stack class, first in, last out

hashtable: more thread safe than hashmap

enumeration: enumeration, equivalent to iterator

Except these, others are non-thread-safe classes and interfaces.

The methods of thread-safe classes are synchronized and can only be accessed one at a time. It is a heavyweight object and has low efficiency.

Others:

1. The difference between hashtable and hashmap

hashtable is thread-safe, that is, hashtable methods provide a synchronization mechanism; hashmap is not thread-safe, that is No synchronization mechanism is provided; hashtable does not allow inserting null values, hashmap does!

2. What to do if multiple threads modify a collection concurrently

Use the old Vector/Hashtable class

StringBuffer is thread-safe, while StringBuilder is thread-unsafe. Without an in-depth understanding of safety and insecurity, it is easy to create the illusion that all operations on StringBuffer are thread-safe. However, the thread-safety guaranteed by Java to you means that its method execution is exclusive. , rather than multiple calls to the object itself, it is still safe. Look at the example below. There is a data member contents in StringBufferTest, which is used for expansion. Each append is thread-safe, but the combination of multiple appends is not thread-safe. The output result is not too controllable. Yes, but if you add the keyword synchronized to the log and getContest methods, the results will become very organized. If you change to StringBuider or even append halfway, it will also give way to other threads operating on this basis:

public class StringBufferTest {
  private StringBuffer contents = new StringBuffer();
  public void log(String message){
   contents.append(System.currentTimeMillis());
   contents.append("; ");
   contents.append(Thread.currentThread().getName());
   for(int i=0;i<10000;i++){
    contents.append(i);  
     contents.append(message);  //append本身是线程安全的,修改contents时,其它线程无法访问。
     contents.append("\n");
   }
   contents.append("\n\n");
  }
  public void getContents(){
   System.out.println(contents);
  }
}
 
class RunThread extends Thread{
  String message;
  StringBufferTest buffer;
  public RunThread(StringBufferTest buffer, String message){
   this.buffer = buffer;
   this.message = message;
  }
  public void run(){
   while(true){
     buffer.log(message);
     buffer.getContents();
   }
  }
  public static void main(String[] args) {
   StringBufferTest ss = new StringBufferTest();
   new RunThread(ss, "you").start();
   new RunThread(ss, "me").start();
   new RunThread(ss, "she").start();
  }
}
Copy after login

The methods of StringBuilder and StringBuffer are exactly the same, it is a multi-threaded and a single-threaded problem. When a thread calls the append method of the same StringBuffer, it has nothing to do with whether it is thread-safe. Unless your result is that the appended series of strings are messed up, then it means that it is thread-unsafe. Thread safety means that only one thread can access critical resources at any time. Thread safety does not mean that his series of operations are synchronized, but that other threads are not allowed to change when he executes a certain method. Whether a class is thread-safe depends on it. Multiple threads are running at the same time, and these threads may execute a certain method at the same time. But the result of each operation is the same as that of single-thread execution, so it can be said to be thread-safe. Because the log method is not locked, everyone may get execution fragments of the CPU after the append lock is released.

But don’t misunderstand multi-thread safety:

public String toString(){
  StringBuffer buffer = new StringBuffer();
  buffer.append(&#39;<&#39;);
  buffer.append(this.name);
  buffer.append(&#39;>&#39;);
  return buffer.toString();
 }
Copy after login

This code is completely thread-safe. The variables defined inside the method will create this local variable when each thread enters. ! There are no thread safety issues involved. Generally, variables related to system security are generally member variables! The internal implementation of stringBuffer itself is site-safe! Thread safety means that the functions provided by the class itself are safe. That is, if you insert a string, then this string insertion is safe, but you have to insert two strings, and you decide the order of the two strings. If there are other insertion errors in the meantime, it will not matter the class. Yes Problem with your own code.

Thank you for reading, I hope it can help you, thank you for your support of this site!

For more articles about thread safety related to classes in Java collections, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

In Java remote debugging, how to correctly obtain constant values ​​on remote servers? In Java remote debugging, how to correctly obtain constant values ​​on remote servers? Apr 19, 2025 pm 01:54 PM

Questions and Answers about constant acquisition in Java Remote Debugging When using Java for remote debugging, many developers may encounter some difficult phenomena. It...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? Apr 19, 2025 pm 07:15 PM

Discussing the hierarchical architecture problem in back-end development. In back-end development, common hierarchical architectures include controller, service and dao...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

See all articles