Java Interview Preparation multi-threading

Source: Internet
Author: User

What does thread safety mean? Examples Show

This class is thread-safe when multiple threads access a class, regardless of how the runtime environment is scheduled or how those threads will be executed alternately, and if no additional synchronization or collaboration is required in the keynote code, and the class behaves correctly. Stateless objects, for example, must be thread-safe.

The difference between a process and a thread

Scheduling: Threads are the basic unit of dispatch, and processes are the basic units of resources. Switching between threads in the same process does not cause the process to switch, and thread switching in different processes causes the process to switch. Owning resources: A process is the basic unit of resources, and threads do not normally own resources except their own stacks. Instead, the resources in the same process are shared with other threads. System overhead: Because the system allocates and reclaims resources, such as memory space, I/O devices, and so on, when the process is created or revoked, the operating system spends much more than the cost of creating or revoking processes.

The understanding of volatile

volatile itself : volatile is a lightweight synchronized, which guarantees the "visibility" of shared variables during multi-processor development, and visibility refers to when a shared variable of a thread changes, The other thread is able to read the modified value. The variable modified by the Voaltile variable writes the data of the current processor cache row back to system memory at the time of the write operation, under the multi-core processor. To ensure consistency, other processors sniff the data that is propagated on the bus and find that the data has been modified to be invalid for their cached address. Volatile can prohibit reordering, and volatile can maintain the atomicity of read/write operations for a single simple Volatile variable. But there is no guarantee of the atomicity of self-increasing self-reduction.

In terms of memory semantics : The write-read of a volatile variable and the release of the lock-get the same semantics, the volatile write has the same memory semantics as the release of the lock, and the volatile read has the same semantics as the acquisition of the lock. Thread A writes a volatile variable, essentially thread A sends a message to a thread that is going to read the volatile variable, B reads a volatile variable, essentially thread B receives a message from a previous thread. Thread A writes a volatile variable, and then thread B reads the variable, which essentially threads a sends a message to B through memory. The implementation of memory semantics is also a non-reordering feature: In order to implement volatile memory semantics, JMM limits the volatile reordering: 1. When the second operation is volatile, it cannot be reordered, regardless of the first operation. 2. When the first action is a volatile read, no matter what the second action is, it cannot be reordered. 3. When the first action is volatile write, the second operation is volatile read, not reordered. In order to implement volatile memory semantics, when the compiler generates bytecode, a memory barrier is inserted into the instruction sequence to suppress a particular type of handler reordering. JMM adopt a Conservative strategy.

    1. Insert a storestore barrier in front of each volatile write operation
    2. Insert a storeload barrier behind each volatile write operation
    3. Insert a loadload barrier behind each volatile read operation
    4. Insert a loadstore barrier behind each volatile read operation
The implementation mechanism of atomicity

The processor provides bus locking and cache locking in two ways to ensure the atomicity of complex memory operations. Overall Linetype: is to use the processor to provide a lock signal, when a processor in the bus to transmit signals, the other processor requests will be blocked, then the processing exclusive memory. So the bus lock overhead is large. Cache Lock: If the memory area is cached in the cache line and locked during lock, the processor bus is not locked but the atomic of the guaranteed operation is blocked by modifying the internal memory address and using the cache consistency system when it performs a locking operation that writes back to memory. Cache consistency binary more than two processors modify memory area data at the same time, and other processor writeback is locked and invalidates its cached rows.

The implementation principle of Java atomic operation

Using the cyclic CAS for atomic operations, CAS is comparing the old values during operation, and if the old values have not changed, they are converted to new values, and the changes are not exchanged. This approach produces the following problems: 1. ABA problem, by adding version number to solve; 2. The cycle time is too long overhead, the general use of spin way to achieve; 3. Only atomic operations of a shared variable can be guaranteed.

Java memory model

The Java memory model controls communication between threads, determining when a thread's write to a shared variable is visible to another thread. It is a language and memory model that ensures that programmers are guaranteed consistent memory visibility over different compilers and different processing platforms by prohibiting certain types of compilers from reordering and processing. JMM's core goal is to find a good balance between providing the programmer with sufficient memory visibility guarantees (providing Happens-before rules), and, on the other hand, loosening the compiler and processor limits as much as possible (as long as the program results are not changed, how to optimize them)

Visibility Assurance in order to provide memory visibility assurance, JMM assures programmers of the following Hapens-before rules: 1. Program Order rules: Each action of a thread happen-before any subsequent action with that thread. 2. Monitor lock rule: the unlocking of a lock, happens-before the locking of the subsequent lock. 3.Volatile variable rule: Writes to a volatile field, happens-before to any subsequent reading of this field. 4. transitivity, if a happens-before B, and B happens-before C then a happens-before C 5. Thread Start rule: If thread A performs an action Threadb.start (). Then any action in thread a happens-before with any action in thread B. 6. Thread End rule: Any action in a thread must be executed before its thread detects that the thread has ended, or it returns successfully from Thread.Join, or returns False when Thread.isalive is called. 7. Interrupt rule: When a thread calls interrupt on another thread, it must be executed before the interrupt thread detects the interrupt call (by throwing interruptedexception, or call isinterrupted and interrupted) 8. Finalizer rule: The constructor of the object must be completed before the finalizer of the object is started.

prohibit reordering to ensure memory visibility, the Java editor inserts a memory barrier directive at the appropriate location in the generated instruction sequence to suppress the ordering of specific types of handlers. Reordering: A means by which compilers and processors reorder instructions in order to optimize program performance. 1) Compiler-Optimized reordering: The compiler can rearrange the order of statements without changing the semantics of the single-threaded procedure. 2) reordering of instruction-level parallelism. Modern processors use instruction-level parallelism to overlap multiple instructions. If there is no data dependency, the processor can change the order in which the corresponding instructions are executed. 3) memory system reordering. Because the processor uses the cache and read/write buffers, this makes the load and storage operations appear likely to be executed in a disorderly sequence.

Memory semantics for final fields

There are two reordering rules for the final domain compiler and the processor: 1. Writes to the final field within the constructor function, and then assigns a reference to the constructed object to a reference variable, the two operations cannot be reordered. (The final domain of the object has been properly initialized before the object reference is guaranteed to be visible to any thread) 2. The first time you read an object reference that contains a final field, the two operations cannot be reordered with the first read of the final field. Why guarantee its memory semantics: it can provide security assurances to Java programmers, so long as the object is properly constructed, it is not necessary to use synchronization to ensure that the thread can see the value of the fianal domain after it has been initialized in the constructor.

Common ways to avoid deadlocks:

1) A thread can inevitably acquire multiple locks at the same time 2) to avoid a thread in the lock to occupy multiple resources, as far as possible to ensure that each lock occupies only one resource 3) try to use a timed lock, use Lock.trylock (timeout) to replace the use of internal locking mechanism. 4) to the database lock, lock and unlock must be in a database connection, or there will be a failure to unlock the situation.

What are the necessary conditions for deadlocks? How to overcome?

A: Four prerequisites for generating a deadlock: a resource can only be used by one process at a time. request and hold condition : When a process is blocked by a request for resources, it remains in place for the resources that have been obtained. Non-deprivation : the resources that the process has acquired cannot be forcibly stripped until the end of use. cyclic wait condition : A cyclic waiting resource relationship is formed between several processes. These four conditions are necessary for the deadlock, as long as the system has a deadlock, these conditions must be established, and as long as one of the above conditions is not satisfied, there will be no deadlock.

Deadlock resolution: A undoes all processes that are deadlocked, and B undoes the deadlock process one by one until the deadlock does not exist, and C forces the resource to be discarded one by one from the deadlock process until the deadlock disappears. D forcibly deprive a sufficient number of resources from other processes to allocate to the deadlock process to unlock the deadlock state

The difference between countdownlatch (latching) and cyclicbarrier (fence)

Countdownlatch: Allows one or more threads to wait for another thread to complete the operation. Cyclicbarrier: Blocks a group of threads until an event occurs.

    1. Latching is used to wait for the event, the fence is waiting for the thread.
    2. The latching Countdownlatch do a minus count, while the fence cyclicbarrier is counted.
    3. Countdownlatch are disposable and cyclicbarrier can be reused.
    4. Countdownlatch a thread (or multiple), waiting for another n thread to complete something before it can be executed. Cyclicbarrier is n threads waiting for each other, before any one thread finishes, all the threads must wait. Countdownlatch is the counter, the thread completes one to remember one, just like a count off, just is descending. And the cyclicbarrier is more like a sluice, the thread executes like a water flow, is blocked at the gate, until the water is full (thread-to-line), it begins to vent.
The difference between execute and submit

Execute () is used to submit objects that do not need to return a worthwhile task, submit () to commit a task that requires a return value, and play the future type.

The difference between shutdown and Shutdownnow

They all work by traversing the worker threads in the thread pool and then calling the thread's Internet method one by one, so that a task that cannot respond to the interrupt may never be terminated. Shutdownnow first sets the status of the thread pool to stop, and then tries to stop all the tasks that are being performed or paused and returns a list of pending tasks. Instead, shutdown simply sets the thread pool to the shutdown state, and then interrupts the threads that are not performing the task.

Threadlocal's design concept and role.

Threadlocal is not a thread, but a local variable of thread, and when you use threadlocal to maintain a variable, threadlocal provides a separate copy of the variable for each thread that uses the variable, so each thread can independently change its own copy. Without affecting the replicas of other threads

http://blog.csdn.net/lufeng20/article/details/24314381

Synchronous

Synchronization is a coordinated pace, in order to operate in a predetermined sequence.

Sleep () and wait () differences

A: The Sleep () method is a static method of the thread class (thread) that causes this thread to pause execution for a specified time, and will execute the opportunity to other threads, but the monitoring State remains, and then automatically resumes when the thread returns to ready state, because calling sleep does not release the object lock. Wait () is the method of the object class that calls the wait () method on this object to cause this thread to discard the object lock (the thread pauses execution) and into the waiting lock pool waiting for this object, only the Notify method is emitted for this object (or Notifyall) After this thread enters the object lock pool ready to get the object lock into the ready state.

difference between sleep () and yield ()

The ①sleep () method gives other threads the opportunity to run without taking into account the priority of the thread, thus giving the low-priority thread a chance to run, and the yield () method only gives the same priority or higher priority to the thread that runs the opportunity; ② thread executes sleep ( ) method to the blocking (blocked) state, and the yield () method is transferred to the Ready state, and the ③sleep () method declaration throws interruptedexception, and yield () The method does not declare any exceptions, and the ④sleep () method is more portable than the yield () method, which is related to the operating system.

Thread synchronization-related methods.

Wait (): Causes a thread to be in the waiting (blocking) state and releases the lock on the held object; Sleep (): A static method that causes a running thread to be asleep Call this method to catch the interruptedexception exception; notify (): Wakes up a waiting thread, and of course, when this method is called, it does not actually wake up a waiting state thread, but the JVM determines which thread to wake, and is not related to priority; Notityall (): Wakes all the threads that are in the waiting state, noting that they are not a lock for all wake-up threads, but rather that they compete;

What is a thread pool (thread pool)

A: In object-oriented programming, it takes time to create and destroy objects because you create an object to acquire memory resources or other resources. More so in Java, virtual machines will attempt to track each object so that it can be garbage collected after the object is destroyed. Therefore, one of the means to improve the efficiency of the service process is to minimize the number of objects created and destroyed, especially the resource-intensive object creation and destruction, which is the cause of "pooling resource" technology. The thread pool, as its name implies, creates a number of executable threads in a pool (container), takes the threads out of the pool without having to create them, uses them without destroying the threads and puts them back into the pool, reducing the overhead of creating and destroying the thread objects.

Http://www.cnblogs.com/dolphin0520/p/3932921.html

Concurrenthashmap Implementation principle

The main difference between Concurrenthashmap and Hashtable is the granularity of the lock and how it is locked. HASHTABL is inefficient in a competitive environment because a lock locks the entire table, causing all threads to compete for a lock at the same time. The CONCURRENTHASHMAP uses a segmented lock, each locking a segment in the container. So many threads can access the different segment data in the container without competition, thus effectively improving the efficiency of concurrent access. The first is to layer the data in multiple segment stores, and assign a lock to each segment, and other threads can access the data of other segments when one of the threads spans one piece of data.

Data structure: Concurrenthashmap internal is composed of segment array and hashentry array. A concurrenthashmapmap contains an array of segment, and the structure of segment, like HashMap, consists of an array and a list structure, so a segment inside contains an Hashentry array. Each hashentry is a linked list structure, and the segment lock that corresponds to the hashentry array needs to be acquired first when it is modified. By default there are 16 segment

segment: Use the Wang/jenkins hash variant algorithm to hash the hashcode of an element once, in order to reduce the hash conflict.

Concurrenthashmap operation: 1.) Get get operation implementation is very simple and efficient. Pass through the hash first, then use the hash value to locate the segment by hashing, and then locate the element by hashing the algorithm. Get is efficient because the entire get process does not need to be locked, unless reading a null value will lock the accent. The technical guarantee of realizing this technology is to ensure that the hashentry is immutable. The first step is to access the count variable, which is a volatile variable, and since all modifications are made to the last step of writing the count variable in a structural modification, this mechanism guarantees that the get operation will be able to get almost the latest structural updates. For non-structural updates, that is, the change in the node value, because the value of the hashentry variable is volatile, it can also be guaranteed to read the most recent value. The next step is to traverse the hash chain according to hash and key to find the node to get, if not found, directly to return NULL. The reason to traverse the hash chain without locking is that the chain pointer next is final. But the head pointer is not final, which is returned by the GetFirst (hash) method, which is the presence of values in the table array. This allows GetFirst (hash) to return obsolete header nodes, for example, when the Get method is executed, after the GetFirst (hash) is executed, the other thread performs the delete operation and updates the header node, which results in the header node returned in the Get method not up-to-date. This is allowed, through the coordination mechanism of the count variable, that get can read to almost the latest data, although it may not be up to date. To get the latest data, only full synchronization is used. 2.) Put this method is also carried out in the case of holding Zhi (lock the current segment), which is, of course, for concurrency security, modify the data can not be carried out concurrently, must have a judge whether the overrun statement to ensure that the capacity is not sufficient to be able to rehash. First, the calculated hash value is positioned to segment and the hash bucket in the segment. Next, determine if there is a node of the same key, and replace the value of the node directly if it exists. Otherwise create a new node and add it to the head of the hash chain, so be sure to modify the value of Modcount and count, and also modify the value of count to be the last step. 3) Remove Hashentry In addition to the value is not final, the other values are final, which means that the node cannot be added or removed from the middle or tail of the hash chain, because this requires modifying the next reference value, and all the node modifications can only start from the head. For put operations, they can be added to the head of the hash chain. However, for the remove operation, you canIt is necessary to remove a node from the middle, which requires that all the nodes in front of the node to be deleted be replicated over and over, and the last node points to the next one to delete the nodes. First locate the node e that you want to delete. If the node does not exist, it returns NULL, otherwise it is necessary to copy the nodes in front of e, and the tail node points to the next node of E. The nodes behind the e do not need to be duplicated, they can be reused. 4) Size () Each segment has a count variable, which is a volatile variable. When the size method is called, first try 2 times by not locking segment the count of each segment is worth the sum, if two times the value is different will lock the entire concurrenthashmap and then calculate. See the art of Java concurrency programming P156 http://www.cnblogs.com/ITtangtang/p/3948786.html

Several available states for a thread

A thread has 6 different states in the running cycle.

    1. New Create
    2. RUNNABLE running state, operating system running and ready in the two states collectively known as running
    3. BLOCKED Blocking State
    4. Waiting wait Status
    5. Time_waiting Timeout Wait
    6. TERMINATED Termination Status
What is the difference between a synchronization method and a synchronized code block
    1. The synchronization method can only lock the current object or class object, and the synchronous method block can use the other object, the current object, and the class of the current object as the lock.
    2. From the results of the anti-compilation, the Monitorenter and monitorexit instructions are used for the synchronization block, while the synchronous method relies on the modifier acc_synchronized on the method, but their essence is to obtain an object monitor. And this acquisition process is exclusive.
The same and difference between the display lock Reentrantlock and the built-in lock synchronized

Same: The display lock has the same semantics as the built-in lock on lock and memory (mutually exclusive access critical section) is different: 1. Use, built-in no need to specify a release lock, simplify the lock operation. Display locks have the operability of lock acquisition and release. 2. Function: The display lock provides many other features such as timed lock waits, interruptible lock waits, fairness, attempted non-blocking acquisition of locks, and implementation of unstructured locking. (When a thread acquires a lock that is blocked outside of synchronized, it interrupts the thread, at which point the interrupt is expressed as being modified, but the thread is still blocked on synchronized, waiting to acquire the lock.) 3. Handling of Deadlocks: The built-in can only be restarted and the display can avoid 4 by setting the timeout to acquire the lock. Performance: java1.5 display far ultra-built, java1.6 display lock slightly better than built-in

    1. Understanding and Using keywords for thread-safe operations such as atomicinteger and volatile

SOF you have encountered in what circumstances.

    1. 3 Ways to implement Multithreading: Thread and runable. 1) Inherit tread class, rewrite run function 2) Implement Runnable interface 3) Implement callable interface
    1. Thread synchronization methods: Sychronized, Lock, Reentrantlock, and so on.

    2. Lock level: Method Lock, Object lock, Class lock.

    3. ThreadPool usage and advantages.

The difference between callable and runnable

  1. Concurrent other things in the bag: Arrayblockingqueue, Countdownlatch and so on.

  2. foreach is compared to normal for loop efficiency.

  3. The reflection acts on the principle.

  4. Generic common features, list can be converted to list.

  5. Design Patterns: Singleton, factory, adapter, responsibility chain, observer, etc.

  6. The use of JNI. How the Java agent is implemented
  7. Java1.7 with 1.8 new features. LMBDA expression Java8 New attribute connection pooling using what data structure to implement connection pooling end a thread what's the method? Interrupt the bottom of the implementation have seen it? What is the status of the thread? What would you do if you realized? Is there a memory leak in Java? What's the situation? Why not cycle count? What are the different ways to lock Aio and bio in Java producers and consumers, handwritten code
  8. The difference between the start () method and run () is called directly after the Java thread is created
  9. Common thread pool patterns and usage scenarios for different thread pools
  10. Newfixedthreadpool this kind of thread pool will do if the number of threads reaches the maximum value, the underlying principle.
  11. Multi-threaded communication between the synchronization problem, synchronized lock is the object, stretch out and synchronized related to a lot of specific problems, such as the same class different methods have synchronized lock, whether an object can be accessed at the same time. Or the static construction method of a class plus the effect of a lock after synchronized.
  12. Understand the implications of reentrant locks, and the difference between Reentrantlock and synchronized
  13. Synchronized data structures, such as Concurrenthashmap's source understanding and internal implementation principles, why he is synchronous and highly efficient
  14. Inter-thread communication, wait and notify

  15. Use of timed threads

  16. Scenario: In a main thread, a large number of (many) sub-threads are required to execute before the main thread finishes. Many ways to consider efficiency.
  17. Concurrent, synchronized interfaces or methods
  18. The use of common classes under J.U.C. An in-depth study of threadpool; the use of blockingqueue. (The difference between take,poll, put,offer); The implementation of atomic classes.
  19. A simple introduction to the situation of multithreading, starting with the creation of a thread. Then how to control the synchronization process, multithreading common methods and structure
  20. There are several ways to implement multithreading, multi-threaded synchronization How to do, say a few lines thread commonly used methods
Write a producer consumer model.
 Public classProducerconsumerpattern { Public Static voidMain (String args[]) {blockingqueue Sharedqueue=NewLinkedblockingqueue (); Thread Prodthread=NewThread (NewProducer (sharedqueue)); Thread Consthread=NewThread (NewConsumer (sharedqueue));     Prodthread.start ();    Consthread.start (); }}//Producer Class in JavaclassProducerImplementsRunnable {Private FinalBlockingqueue Sharedqueue;  PublicProducer (Blockingqueue sharedqueue) { This. Sharedqueue =Sharedqueue; } @Override Public voidrun () { for(inti=0; i<10; i++){            Try{System.out.println ("Produced:" +i);            Sharedqueue.put (i); } Catch(Interruptedexception ex) {Logger.getlogger (Producer.class. GetName ()). log (Level.severe,NULL, ex); }        }    }}//Consumer Class in JavaclassConsumerImplementsrunnable{Private FinalBlockingqueue Sharedqueue;  PublicConsumer (Blockingqueue sharedqueue) { This. Sharedqueue =Sharedqueue; } @Override Public voidrun () { while(true){            Try{System.out.println ("Consumed:" +Sharedqueue.take ()); } Catch(Interruptedexception ex) {Logger.getlogger (Consumer.class. GetName ()). log (Level.severe,NULL, ex); }        }    }}

Java Interview Preparation multi-threading

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.