-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultithreadingJavaNotes
More file actions
93 lines (61 loc) · 2.41 KB
/
MultithreadingJavaNotes
File metadata and controls
93 lines (61 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//This file contains my notes on Multithreading in Java.
1. Two basic ways of creating threads in Java:
a. Extend Thread Class
b. Implement Runnable interface and pass it to the constructor of the Thread class
--check
thread.start();
thread.join();
Executor Services : thread pool --Check
Basic Thread Synchronization:
If two or more thread sharing the same data, two problems may occur:
1. Data being cached
2. Thread interleaving
Volatile keyword prevents from data being cached --Check
private volatile boolean running;
synchronized keyword to prevent interleaving
Every object in Java has intrinsic lock/monitor lock/mutex --check
It's not always ideal to have just one intrinsic lock...you may want multiple locks?? --check
=============
Producer Consumer
BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(10);//creates an array of 10 ints
BlockingQueue class is thread safe.
queue.put(intValue); //Waits if queue is full
queue.take(); //waits if queue is empty
=================
wait() and notify()
wait()
- hands over the control of lock of synchronized block it's called in
- method of object class. So use it with the object you're acquiring a lock with.
- use wait(timeout) cause wait() can cause thread to wait indefinitely
- wait() is more efficient than running a while loop which keeps checking a flag value
- can call wait() only in synchronized code blocks/methods --check
notify()
- can only be called from a synchronized code block/method
- doesn't relinquish the lock like wait(). --check
lock will be relinquished only when the current threads execution is over.
notifyall()
============
Q: Inheritance
List<Integer> list = new LinkedList<Integer>();
can list reference access methods which are defiend in LinkedList class but not in List class??
Reason of this question:
I can't use list.removeFirst();
but if the object is like below:
LinkedList<Integer> list = new LinkedList<Integer>();
then I can use list.removeFirst();
======
Semaphores
Semaphore sem = new Semaphore(10);
sem.release();
sem.acquire();
ExecutorService executor = new Executors.newCachedThreadPool();
executor.submit( new Runnable() { /*override run() method */ } );
executor.shutdown();
executor.awaitTermination(1, TimeUnit.DAYS);
======
Callable and Future
==============
Interrupting Threads
2nd tutorial in series
how to gracefully stop a thread using volatile boolean flag
: probably the best way to stop a thread in Java