1. How to stop a thread
-
The stop method can stop a thread, but this method is not thread-safe and involves locking security issues, so it has been officially deprecated, so it cannot simply stop a thread.
Why can’t you simply stop a thread?
When a thread executes a task, it will occupy CPU and memory resources and lock these resources. If we want to terminate the thread abnormally, the current thread will not have time to clean up the resources, and the next thread will generate an exception message when accessing the current resource.
-
Logically stop the task executed in the thread, although the thread can not stop, but the task is ok, task and thread are bound to each other, that is, a collaborative task execution mode. Instead of adding stop methods to threads, we should add stop logic to tasks.
Interrupts are handled in the following ways:
Interrupt, volatile Boolean Indicates the flag bit
-
Interrupt: System-level interrupt mode
After calling Thread.interrupt, if the currently executing logic throws InterruptException, we can terminate the task at the point where we catch the current exception. If we do not catch an exception, If interrupted or isInterrupted is used to terminate the current task.
Interrupted: Static method that retrieves the interrupted status of the current thread and clears it.
- The current running thread
- False is returned after repeated calls;
IsInterrupted: A non-static method that obtains the interrupted status of the thread without clearing it.
- The thread corresponding to the thread object called
- Repeatable, interruptible always returns true
The difference between interrupted and isInterrupted is due to the underlying logic of JNI. In interrupted, a method of clearing is added and a lock is placed on the method.
-
Volatile Boolean Indicates the flag bit
Boolean flag, in the process of thread calls we can add a tag to the currently executing task for processing, if when the logo change, they do not need to continue to perform the task, terminate the task in time, and make the corresponding processing, but this kind of situation will have problems with visibility between threads, that is to say we change the value, Because of the Java VIRTUAL machine’s memory model, each thread must copy data from main memory to the working interval, modify the value and then synchronize it back to main memory. Therefore, the Boolean flag must be volatile to tell the virtual machine that the current property is volatile.
-
2. How to write a thread safe program
-
What is thread safety
Variable resource (memory) sharing between threads
-
How to implement thread-safe programs
-
Not sharing resources
Reentrant functions that do not perform any memory in between and return the data directly after the operation
ThreadLocal:
A ThreadLocalMap is bound to a thread and stored internally by a ThreadLocalMap. The key is the ThreadLocal and the value is the value we want to store.
ThreadLocalMap WeakHashMap Object to hold A weak reference A weak reference The object of GC Does not affect the Does not affect the Reference to clear Cleared when the thread exits Removed after GC (ReferenceQueue) Hash conflict Open addressing Singly linked list method The Hash computation Multiples of the magic number Object Hashcode hash Applicable scenario The object is less general Usage suggestions:
- Declared as a static final member, only one member is needed globally
- Avoid storing a large number of objects, because inside it is a map
- Remove objects as soon as they are finished
-
Share immutable resources
Reordering is prohibited. When we create an object, non-final members of the object may be assigned outside of the constructor, which means that the code is executed ina different order. This will result in an exception to the output.
Final features:
- A member variable defined as final cannot be changed
- Classes defined as final cannot be integrated, and all of their internal methods are hidden with the final keyword added
- Methods defined as final cannot be overridden
- The final keyword can be used to disable reordering
- Jdk1.8 before if we want in an anonymous inner class needs to access external local variables, so the local variable must use the final modification, because of the anonymous inner class access outside of the local variable is the value of the local variable copy into the inner class to use, if not defined as final, so when the outside of the local variable value change, However, if the value inside the inner class does not change, the result of the program may be abnormal.
- Jdk1.8, after an anonymous inner class access external local variables of a class, then the local variable is no longer need to define a final, because of its internal maintains external references, including the variable values in call, is actually external instance of a class to call, that is two instances refer to the same memory address, guarantee the data consistency
-
Sharing mutable resources
-
visibility
Final, volatile, lock release forces the cache to be flushed to main memory, so if you want to ensure visibility by locking, you need to lock the same thread.
-
Operational atomicity
Note that a++ is not an atomic operation
- Lock to ensure mutual exclusion of operations
- Using CAS directives, the underlying principles are the Unsafe class and spin locks
- Using atomic value types
- Using atomic attribute updater (AtomicReferenceFieldUpdater)
-
Disallow reordering
Final, volatile,
-
-
3. How does ConcurrentHashMap support concurrent access
1. Version iteration process
- JDK5: subsection locking
The hash algorithm uses high values to find segments and low values to find values in the table corresponding to the current segment.
Defect:
When an integer less than 30,000 is passed in, the hash value is always 15, so when searching for a segment, only the last segment will be found, losing the advantage of segment locking.
-
JDK6: Optimizes the quadratic Hash algorithm
When calculating the hash value, the high and low bits are evenly distributed.
-
JDK7: seglazy loading, volatile & CAS
If CHM is instantiated in jdk7, all segments will be initialized
-
JDK8: Discard segments and implement concurrent implementation based on HashMap principle
Delete segment from table and lock table
2. How to count CHM
- Jdk5-7 sums based on the number of segment elements, and locks if the number is different twice
- JDK8 introduces CounterCell, which is also segmented counting in nature
3.CHM is weakly consistent
- You may not be able to read the element immediately after you add it
- You might still have elements after you’ve cleaned them out
- Iterating through the previous segment element changes will read
- Segment element changes after traversal cannot be read
- Changes in traversal elements do not throw exceptions
4. The HashTable shortcomings
- Large lock: Lock a HashTable object
- Long lock: Locks methods directly
- Read-write lock sharing: There is only one lock, locked from head to tail
5. CHM solutions
- Small lock: Segmented lock (5-7) Bucket node lock (8)
- Shortening: Attempts to acquire the lock, fails and then adds the lock
- Split read/write locks: read failures followed by locks (5-7), volatile read/CAS write (7-8)
6. How to optimize locks
- Short locks are better than long locks: Try to lock only what is necessary
- Big locks are worse than small locks: split the locked object as much as possible
- Public locks are not as good as private locks: put lock logic in private code whenever possible
- Nested locks are inferior to flat locks: Avoid nested locks whenever possible when designing your code
- Separate read/write lock: Read more times than write
- Coarse-high frequency locks: If possible, combine locks that are too frequent and short
- Eliminate useless locks: Do not lock as much as possible. Use volatile and CAS instead
Multithreaded communication summary list
Android multithreaded communication summary one
Android Multithreaded communication summary ii -IntentService
Android Multithreaded communication Summary three – interview must ask Handler
Android multithreaded communication summary four
I’m Android master. Success isn’t about how much you own, it’s about how many people you’ve helped and how many lives you’ve touched. Thank you, and I’ll see you next time.