The foundation is the top priority ~ Thread-safe Hashtable

Source: Internet
Author: User

Hashtable indicates a set of Key/Value pairs. These Key/Value pairs are organized based on the hash code of the Key. The Key cannot be null, and the Value can be null, this is different from Hashmap (it is not thread-safe). For Hashtable, it implements the IDictionary and ICollection interfaces. Its key and value are of the object type and do not support generics, to convert data types into boxing and unboxing, this will certainly have some impact on the performance. Therefore, Microsoft provides a set of key-value pairs that support generics, the Dictionary itself is not thread-safe. We need to lock it to avoid some errors in the multi-threaded environment.

Next let's take a look at the thread-safe Hashtable code snippet:

            Hashtable ht = Hashtable.Synchronized(, ]);

Let's take a look at the Dictionary object, which can make the Attributes provided by its base class to implement thread security of its internal objects.

            Dictionary<, > dic =  Dictionary<, > ((dic , 

The following is an example of Dictionary thread security. We have two threads, t1 and t2. When we lock it, T1.

 

            Dictionary<, > dic =  Dictionary<, >=  Thread(() => ((dic  ICollection).SyncRoot) , );=  Thread(() => ((dic ] = ;);

 

For Hashtable, if you want to lock it by writing and reading, you can also implement it by locking it in the code segment.

                  Thread t1 =  Thread(() =>

OK. Let's talk about the thread security of hashtable. Finally, let's talk about the knowledge of thread security, because the program you wrote must be

In a multi-threaded environment.

 

 

Related Article

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.