Home  >  Article  >  Java  >  Classes in Java collections about thread safety

Classes in Java collections about thread safety

高洛峰
高洛峰Original
2017-01-23 16:42:501205browse

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();
  }
}

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();
 }

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:
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