Java multi-thread interview questions

Source: Internet
Author: User

Java multi-thread interview questions

1. What is the difference between ArrayList and Vecoter?

Similarities and differences between Array and ArrayList
I. Differences between Array and ArrayList
#1. variables of the Array type must be instantiated at the same time (at least the size of the Array must be initialized), while ArrayList can only be declared first.
For example:
Int [] array = new array [3];
Or int [] array = {1, 2, 3 };
Or ArrayList myList = new ArrayList ();
These are legal, but using int [] array directly cannot.

#2. Arrays can only store homogeneous objects, while ArrayList can store heterogeneous objects.
Homogeneous objects refer to the objects of the same type. If an array declared as int [], only integer data can be stored, and string [] can only be stored in plain data, except for arrays declared as object.
The ArrayList can store any different types of data (because it stores packed Object objects, in fact, the ArrayList uses "object [] _ items; "Such a private field to encapsulate the object)

#3 storage method in CLR hosting pair
Array is always stored continuously, and the storage of ArrayList is not necessarily consecutive.

#4 initialization size
The size of the Array object must be specified only during initialization, and the size of the created Array is fixed. The size of the ArrayList can be specified dynamically, and the size can be specified during initialization, you can also leave this parameter unspecified, that is, the space of the object can be increased at will.

#5 arrays cannot add or delete items at will, while ArrayList can insert or delete items anywhere.

2. similarity between Array and ArrayList

#1 all have indexes, that is, you can use indexes to directly obtain and modify any items.
#2 all the objects they created are stored in the managed heap.
#3 can enumerate itself (because both implement the IEnumerable interface ).

Note:
In C #2.0, we recommend that you use the standard version of ArrayList, that is, System. collection. the List <T> In the Generics namespace not only ensures the type security, but also improves the object processing efficiency because there is no packing or unpacking process.

 

2. Ensure ArrayList thread security

1. Use the synchronized keyword;

2. Use Collections. synchronizedList (); The usage is as follows:

Assume that the code you created is as follows: List <Map <String, Object> data = new ArrayList <Map <String, Object> ();

To solve this thread security problem, you can use Collections. synchronizedList (), for example:

List <Map <String, Object> data = Collections. synchronizedList (new ArrayList <Map <String, Object> ());

The methods used are almost the same as those of ArrayList. For details, refer to the api documentation;

In addition, ArrayList and javaslist are both an implementation under the interface List, which have the same usage, but the places used are a bit different. ArrayList is suitable for a large number of random accesses, the rule list is suitable for table insertion and deletion. Both are non-thread-safe. The solution is the same as above (to avoid thread security, the above method is used, especially the second method, in fact, it is very performance-consuming ).

2.

Define a class mydomainlist extends extended list
Implement synchronous upload list. addFirst (); and removeLast (); method!
Mydomainlist list = new mydomainlist ();
List listProxy = Collections. synchronizedList (list );
Use the listprocxy method when using a common method ,.....................
Or, you can synchronize all the mydomainlists.

 

 

 

 

4. Why is thread-safe set insecure?

Author: idreamagic
Link: https://www.zhihu.com/question/49855966/answer/149889161
Source: zhihu
Copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

Thread security refers to the multi-thread access. The locking mechanism is used. When a thread accesses a data of this type, it is protected. Other threads cannot access the data until the thread has read the data, other threads can be used. No data inconsistency or data pollution occurs.

Thread security means data access is not protected. It is possible that multiple threads change data successively, resulting in dirty data.

========================================================== ======================================

Concept:

If multiple threads are running simultaneously in the process where your code is located, these threads may run the code at the same time. If the result of each running is the same as that of a single thread, and the value of other variables is the same as expected, it is thread-safe.

In other words, the interface provided by a class or program is an atomic operation for a thread or the switching between multiple threads does not lead to ambiguity in the execution result of this interface, that is to say, we do not need to consider synchronization issues.

Thread security issues are caused by global variables and static variables.

If each thread only performs read operations on global variables and static variables without write operations, this global variable is generally thread-safe. If multiple threads execute write operations at the same time, generally, thread synchronization needs to be considered; otherwise, thread security may be affected.

Security:

For example, an ArrayList class may take two steps to add an element: 1. Store this element at the Items [Size] position; 2. Increase the Size value.

When a single thread is running, if the Size is 0, after an element is added, the element is in the position 0 and the Size is 1;

In the case of multithreading, for example, if there are two threads, thread A first stores the elements in the position 0. However, at this time, the CPU scheduling thread A is paused, and thread B gets the chance to run. Thread B also adds an element to this ArrayList, because the Size is still equal to 0 (note that we assume that two steps are required to add an element, thread A only completes step 1), so thread B also stores the elements in the position 0. Then, both thread A and thread B continue to run, increasing the Size value.

Well, let's take a look at the ArrayList. There is actually only one element, which is stored in the position 0, but the Size is equal to 2. This is "thread unsafe.

Security:

Thread security is not a true or false proposition. The Vector method is synchronous, and the Vector is clearly designed to work in a multi-threaded environment. However, its thread security is limited, that is, there is a State dependency between some methods (Similarly, if the Vector is modified by other threads during iteration, it is determined by the Vector. the iterator returned by iterator () will throw ConcurrentModifiicationException ).

No classification system is widely accepted for common thread security levels in Java classes. However, it is important to record their thread security behaviors when writing classes.

Bloch provides a classification method for describing five types of thread security: immutable, thread security, conditional thread security, thread compatibility, and thread opposition. As long as you clearly record the thread security features, it does not matter whether you use this system. This system has its limitations-the boundaries between various categories are not exactly clear, and in some cases it is not taken care of-but this system is a good starting point. The core of this classification system is whether the caller can or must be surrounded by external synchronization operations (or a series of operations ). The following sections describe the five categories of thread security.

Immutable


Immutable objects must be thread-safe and never require additional synchronization [1]. As long as an unchangeable object is built correctly, its external visible State will never change, and it will never be seen in an inconsistent state. In Java class libraries, most basic numeric classes such as Integer, String, and BigInteger are immutable.

It should be noted that for Integer, this class does not provide the add method, and addition is to use + for direct operations. The + operation is not thread-safe. This is the original atomic operation class AtomicInteger.

Thread Security

The thread-safe object has the attributes described in the "thread security" section above -- the constraints specified by the class specification are still valid when the object is accessed by multiple threads, no extra synchronization is required regardless of how the thread is scheduled in the runtime environment. This thread security guarantee is very strict-many classes, such as Hashtable or Vector, cannot meet this strict definition.


Conditional


Conditional thread security classes can be thread-safe for separate operations, but some operation sequences may require external synchronization. The most common example of conditional thread security is to traverse the fail-fast iterator returned by Hashtable or Vector or the returned iterator. It is assumed that the underlying set will not change during the iterator traversal.. To ensure that other threads do not change the set during traversal, the iterative thread should ensure that it exclusively accesses the set to achieve the integrity of traversal. In general, dedicated access is guaranteed by synchronization of locks-and class documents should indicate which lock (usually the internal monitor of the object (intrinsic monitor )).

If you record a conditional thread security class, you should not only record it as conditional thread security, but also record the operation sequences that must be prevented from concurrent access. Users can reasonably assume that other operation sequences do not require any additional synchronization.

Thread compatibility

The thread compatibility class is not thread-safe, but can be safely used in the concurrent environment by correct use of synchronization. This may mean that each method call is surrounded by a synchronized block, or a wrapper object is created, where each method is synchronized (just like Collections. synchronizedList ). It may also mean that some operation sequences are surrounded by synchronized blocks. To maximize the use of the thread compatibility class, if all calls use the same block, the caller should not be required to synchronize the block. In this way, the thread-compatible objects will be included in other thread-safe objects as variable instances, so that synchronization of their owner objects can be used.

Many common classes are thread-compatible, such as the collection class ArrayList and HashMap, java. text. SimpleDateFormat, or JDBC class Connection and ResultSet.

Thread opposition


The Opposite Classes of threads are those that cannot be safely presented during concurrent use regardless of whether or not external synchronization is called. Thread opposition is rare. When the class modifies static data and static data affects the behavior of other classes executed in other threads, thread opposition usually occurs. An example of a thread opposition class is a class that calls System. setOut.

 

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.