Multithreading implementation
2 ways to implement multithreading:1.implement Runnable, then implement the void run() method.2.extends the Thread abstract class.
Obviously 1st way is better, as Java not allowed extends multi-classes.
Java.util.concurrent
It includes several threadsafing collection framework:CopyOnWriteArrayList,ConcurrentHashMap,ConcurrentSkipListSet,ConcurrentSkipListMap,BlockingQueue
Eg:BlockingQueue is thread safe for consumer/producer problems. Whereas add, remove will throw Exception; offer poll gives out specail value; put/take will get thread blocked until operated successfully.
ConcurrentHashMap providing thread safety and atomicity guarantees.1
2
3
4
5
6
7
8
9
class Solution {
public String main() {
Consumer c= new Consumer();
Producer p = new Producer();
new Thread(c).start();
new Thread(p).start();
}
}
tasks may execute in a newly created thread, an existing task-execution thread, or the thread calling execute, and may execute sequentially or concurrently.
ThreadPoolExecutor and ScheduledThreadPoolExecutor provide tunable, flexible thread pools. The Executors class provides factory methods for the most common kinds and configurations of Executors, as well as a few utility methods for using them. Other utilities based on Executors include the concrete class FutureTask providing a common extensible implementation of Futures, and ExecutorCompletionService, that assists in coordinating the processing of groups of asynchronous tasks.
Implements the ThreadFactory can creates self serving thread class.
Lock in Java
ReentrantLock 实现的锁定规则非常简单 – 每当一个线程具有锁定时,其他线程必须等待,直到该锁定可用。有时,当对数据结构的读取通常多于修改时,可以使用更复杂的称为读写锁定的锁定结构,它允许有多个并发读者,同时还允许一个写入者独占锁定。该方法在一般情况下(只读)提供了更大的并发性,同时在必要时仍提供独占访问的安全性。ReadWriteLock 接口和 ReentrantReadWriteLock 类提供这种功能 – 多读者、单写入者锁定规则,可以用这种功能来保护共享的易变资源。
synchoronized used for methods/coding blocks.synchormized(this){}.非同步代码仍然能继续执行。synchronized锁住的是括号里的对象,而不是代码。main()里面只创建一个new Thread(),thread.start()同步机制才会生效.多个thread是不生效的。synchronized(Sync.class)实现全局锁的效果。
Java.util.concurrent.atomic/locks
Java EE
Servlet is singleton but multi-threading, and is not thread safe.
ConcurrentHashMap
ConcurrentHashMap是J.U.C(java.util.concurrent包)的重要成员,它是HashMap的一个线程安全的、支持高效并发的版本。在默认理想状态下,ConcurrentHashMap可以支持16个线程执行并发写操作及任意数量线程的读操作。
在ConcurrentHashMap中,无论是读操作还是写操作都能保证很高的性能:在进行读操作时(几乎)不需要加锁,而在写操作时通过锁分段技术只对所操作的段加锁而不影响客户端对其它段的访问。特别地,在理想状态下,ConcurrentHashMap 可以支持 16 个线程执行并发写操作(如果并发级别设为16),及任意数量线程的读操作。
- 通过锁分段技术保证并发环境下的写操作;
- 通过 HashEntry的不变性、Volatile变量的内存可见性和加锁重读机制保证高效、安全的读操作;
- 通过不加锁和加锁两种方案控制跨段操作的的安全性。
ConcurrentHashMap读操作不需要加锁的奥秘在于以下三点:
用HashEntery对象的不变性来降低读操作对加锁的需求;
用Volatile变量协调读写线程间的内存可见性;
若读时发生指令重排序现象,则加锁重读;