-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathICT_Questions.txt
More file actions
611 lines (452 loc) · 19.3 KB
/
ICT_Questions.txt
File metadata and controls
611 lines (452 loc) · 19.3 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
What is a race condition ?
A type of error that occurs when 2 or more threads are unable to access and modify a shared resource.
What is a process and a thread in brief ?
Processes are independent programs that are heavyweight and have their own memory space and do not share
memory spaces with other threads, allocated by the OS. When a web browser and another application are
opened at the same time they are 2 different processes and ones activity wont affect the other.
A thread is a smaller more lightweight unit of execution within a process. Threads run concurrently by
the means of multithreading. They are able to access a single shared resource concurrently. An example
could be in a text editor one thread controls the task of handling the typing and another handling the
displaying on the screen.
Why are threads considered lightweight?
Threads within the same process shared the same memory space and resources.
Threads can be created and terminated with ease since they are lightweight compared to processes
Lightweight as they can access shared resources concurrently with minimal resource usage.
JVm provides built in mechanisms and optimizations for thread management.
What is a synchronous action?
Tasks or operations that occur sequentially where one task must finish before the other starts, while
asynchronous tasks can occur concurrently.
The use of the join() function is an example demonstrating synchronous actions between Threads.
What is synchronization ?
A technique used to control the access of threads to shared resources in concurrent programmming
ensuring that only one thread accesses the resource at a time preventing data inconsistency.
What is interleaving ?
The execution pattern where multiple threads or processes are executed in overlapping time slices,
resulting in non-deterministic order of operations.
What is interference ?
A situtation where multiple threads concurrently modify shared resources, leading to inconsistency
What is Mutual Exclusion ?
It is a mechanism that achieves synchronization making sure that it prevents race conditions,
and maintains data inconsistency and intergrity when multiple threads need to perform operations
What is a Livelock ?
A situation in which threads or processes continously change their states in response to
each other without making any progress, similar to a deadlock but with active threads
What is a Deadlock ?
A deadlock is a situation where 2 threads are blocked forever where they are waiting for one another
to release a resource.
What are the main features of a Semaphore ? What are it's advantages and disadvantages ? Difference between the Mutex, binary and general semaphore ?
A mutex ensures that only one thread or process can access a resource at a time, essentially a
lock that provides exclusive access.
In a situation where multiple threads need to access a shared resource, like that of a bank account,
the deposit and withdraw methods, the critical sections can only be accessed by one thread at a time.
A Binary semaphore is a semaphore with a value that could only be either 0 or 1, similar to a
mutex but lacks the ownership concept.
The producer consumer problem is a good example of the binary semaphore where the producer Thread
produces data and the consumer thread consumes the data, The producer must signal the consumer that
new data is available.
A General semaphore manages a set number of resoures that can only be accessed by multiple threads
simulataneously, allowing up to a defined limit.
Managing a limited number of database connections for multiple threads, only the database connection
with the equal count will execute while the others remain.
What are the main features of the monitor ? What is the purpose of the while loop in the monitor ?
Another synchronization construct that is used to control access to shared resources where
it ensures that only one thread can execute a particular section of code at a time.
Monitors combine the concept of mutual exclusion with the ability to wait for a certain
condition to become true.
Monitors provide a way for threads to wait for certain conditions to be met before they proceed.
This is often implemented using wait(), notify(), and notifyAll() methods in Java.
Purpose of the while loop in monitors - It rechecks the condition ensuring that the thread only
proceeds when the condition is genuinely satisfied.
(a) After a thread has been created using new, it is in the NEW Thread state & it is an empty
Thread object. No system resources have been allocated to it yet. When a thread is in this state,
you can only start the thread by calling the start() method. Calling any other method besides
start() raises an IllegalThreadStateException.
A new thread is created the moment a thread is extended or when a runnable is implemented by a class
This thread is in the new state. In this state the thread is an empty object in the memory. To transition
to the runnable state the start() method is called, the run() of the body of the thread is then executed.
Other methods such as run(), sleep(), notify() or yield() will cause the thread to run into an
IllegalThreadStateException.
The thread states are the New state which cannot, runnable is the only state where execution can occur,
waiting, timed-waiting, blocked, terminated states the thread is either idle or cannot be executed.
When a thread is blocked from accessing the lock of a critical section it means that the thread
has been executing code and as it moves to a non-runnable state, it is not available to be scheduled
until the lock is released.
If there are several threads waiting to be executed the JVM decides on the execution based on the
priority of the thread where they could vary between 0 belong lowest priority and 5 being the mid
priority and 10 being the max priority. If the JVM comes across threads with the same priority it uses
a round robin fashion of execution.
If a thread is in the TIMED_WAITING state what can happen to it?
If the specified time elapses the thread will automatically move to the runnable state
If another thread calls thread.interrupt() on the thread to interrupt it from sleep.
What is the dining philosopher problem and how is it solved ?
What is the producer consumer problem and how is it solved in brief ?
What is the reader and writer problem and how is it solved ?
The reader writer problem is a generalization of the mutual exclusion problem.
The writers write to the shared resource, modifying it, while the readers read from it. Only writer
can access the shared resource and write at a time while several readers can acces the
shared resource at the same time.
Writers have exclusive access to the resource while writing(no other reader or writer must access)
Multiple readers can access the shared resource concurrently.
Describe the FSP abstract model of a process.
Why is a Java thread described as a lightweight process ?
If several threads are waiting in a queue to get executed how does the JVM decide on which one to execute next ?
When multiple threads are waiting to get executed the JVM decided on deciding which thread gets executed first by
priority and threads could have a priority scale from one to 10 with 5 begin the normal priority.
1 being the minimum priority and 10 being max priority.
Priority doesnt also determine or gurantee the execution of threads always.
Fairness and starvation prevention is considered by the JVM where each thread has to get executed.
The OS has something called as time sclicing where the lower priority threads are given a chance to
execute over the higher priority ones.
How to remember program after program>>>
Threads Basics
3 classes - MyThread / MyRunnable / ThreadsDemo
Both the classes MyThread and MyRunnable have things in common that could be done in one and copied to the other
public class MyRunnable implements Runnable{
public void run(){
for (int i=0; i<10; i++){
System.out.println(Thread.currentThread().getName() + " implemented by: " + i);
try{
Thread.sleep(1000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
public class MyThread extends Thread{
public void run(){
for (int i =0; i<10; i++){
System.out.println(Thread.currentThread().getName() + " extended by: " + i);
try{
Thread.sleep(1000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
public class ThreadDemo{
public static void main(String[] args){
MyThread thread1 = new MyThread();
Thread thread2 = new Thread(new MyRunnable());
thread1.start();
thread2.start();
for (int i=0; i<5; i++){
System.out.println("Main Thread: "+ i);
try{
Thread.sleep(1000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
Thread Transitions
There are 2 classes - MyRunnable class and ThreadStateExamples (Main class)
In MyRunnable class within the for loop we have a synchronized (this) block and there are 2 (try catch) one to displat timed waiting and the other to display waiting with wait()
public class MyRunnable implements Runnable{
@Override
public void run(){
for (int i=0; i<10; i++){
synchronized(this){
try{
Thread.sleep(1000);
} catch (InterruptedExcetion e){
e.printStackTrace();
}
try{
wait();
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
First we create the myRunnable instance from the class MyRunnable that has the run method and pass the instance to the Thread
Display that the thread is in the NEW state
Display that the thread is in the RUNNABLE state after starting the thread
then everything goes into a try-catch block (
put the thread to sleep for 1sec
print that it is in TIMED_WAITING state
then synchronized(myRunnable){
myRunnable.notify(); //notify that the thread is in the waiting state
}
Then put the thread once again to sleep
call thread.join(); to wait for the thread to finish
print the terminated state
)
public class ThreadStatesExample{
public static void main(String[] args){
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
//NEW state
System.out.println("The thread is currently not started but created and is in the : " + thread.getState());
thread.start();
//Runnable state
System.out.println("The thread has started and is in the runnable state: " + thread.getState());
try{
Thread.sleep(1000);
System.out.println("The thread is in the sleeping state: " + thread.getState());
synchronized (myRunnable){
myRunnable.notify();
}
Thread.sleep(1000);
System.out.println("The thread is notified: " + thread.getState());
thread.join(); //Wait for the thread to finish
System.out.println("The thread is terminated and is in the : " + thread.getState());
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
state to transition - New -> Runnable -> Timed waiting -> waiting -> terminated
-----------------Thread Groups ---------------------
Has 2 classes - MyRunnable / ThreadGroupExample
public class MyRunnable implements Runnable{
@Override
public void run(){
try{
while (true){
System.out.println(Thread.currentThread().getName() + " is running");
Thread.sleep(2000);
}
} catch (InterruptedException e){
System.out.println(Thread.currentThread().getName()+ " was interrupted");
}
}
}
public class ThreadGroupExample{
public static void main(String[] args){
ThreadGroup threadGroup = new ThreadGroup("Parent Group");
//Create a child group
ThreadGroup childGroup = new ThreadGroup("Child Group");
Thread t1 = new Thread(parentGroup, new MyRunnable(), "Thread-1);
Thread t2 = new Thread(parentGroup, new MyRunnable(), "Thread-2);
t1.start();
t2.start();
Thread t3 = new Thread(childGroup, new MyRunnable(), "Thread-3");
Thread t4 = new Thread(childGroup, new MyRunnable(), "Thread-4");
t3.start();
t4.start();
System.out.println("Active threads in: "+ parentGroup.getName() + " : " + parentGroup.activeCount());
System.out.println("Active threads in: " + childGroup.getName() + " : " + childGroup.activeCount());
parentGroup.interrupt();
}
}
The methods to remember in this program are the activeCount() and the interrupt()
After creating the ThreadGroup, create the Thread with calling the object from
the ThreadGroup with the MyRunnable() and then make sure to start the thread
Use the getName() function when you need to get the name of the thread
Banking App to understand the synchronized method
Has 4 classes - Account/ App/ Husband/ Wife
public class Account{
private double balance;
private String accNo;
public Account(String accNo, double balance){
this.balance = balance;
this.accNo = accNo;
}
public synchronized balance deposit(double amount){
balance = balance + amount;
System.out.println(Thread.currentThread().getName() + " is the amount deposited: " + amount + " and the balance is: " + balance);
return balance;
}
public synchronized balance withdraw(double amount){
if ( balance >= amount){
balance = balance - amount;
System.out.println(Thread.currentThread().getName()+ " the withdrawn amount is: " + amount + " and the current balance is : " + balance);
return balance;
} else {
System.out.println(Thread.currentThread().getName()+ " insufficient funds.");
}
}
public synchronized double getBalance(){
return balance;
}
public string getAccNo(){
return accNo;
}
}
public class Husband implements Runnable{
private String name;
private Account account;
public Husband(Account account, String name){
this.account = account;
this.name = name;
}
public String getName(){
return name;
}
@Override
public void run(){
for (int i=0; i<5; i++){
try{
account.withdraw(50.00);
} catch (IllegalArgumentException e){
System.out.println(Thread.currentThread().getName()+ " Insufficient Funds");
}
}
}
}
public class Wife implements Runnable{
private account Account;
private String name;
public Wife(String name, Account account){
this.name = name;
this.account = account;
}
public String getName(){
return name;
}
@Override
public void run(){
for (int i=0; i<10; i++){
account.deposit(200.00);
}
}
}
public class App{
public static void main(String[] args){
Account account = new Account("1233", 100.00);
Wife wife = new Wife("Jack", account);
Husband husband = new Husband("Juliet", account);
Thread wifeThread = new Thread(wife, wife.getName());
Thread husbandThread = new Thread(husband, husband.getName());
husbandThread.start();
wifeThread.start();
}
}
Mother-Child Plate Program - Monitors in Java
public class Plate{
private boolean available;
public String food;
public Plate(boolean available, String food){
this.food = food;
this.available = available;
}
public synchronized void produce(String food){
while(available){
try{
wait();
} catch (InterruptedException e){
e.printStackTrace();
}
}
this.food = food;
System.out.println(Thread.currentThread().getName()+ " produced: "+ food);
available = true;
notifyAll();
}
public synchronized String consume(){
while(!available){
try{
wait();
} catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " consumed: " + food);
available = false;
notifyAll();
return food;
}
}
public Mother implements Runnable{
private Plate plate;
public Plate(Plate plate){
this.plate = plate;
}
@Override
public void run(){
for (int i=0; i<5; i++){
String food = "Food at " +i+ "th serve";
plate.produce(food);
}
}
}
public Child implements Runnable{
private Plate plate;
public Child(Plate plate){
this.plate = plate;
}
@Override
public void run(){
for(int i=0; i<5; i++){
String food = plate.consume();
}
}
}
public class Test{
public static void main(String[] args){
Plate plate = new Plate();
Mother mother = new Mother(plate);
Child child = new Child(plate);
Thread t1 = new Thread(mother, "Mother");
Thread t2 = new Thread(child, "Child");
t1.start();
t2.start();
}
}
the methods from the monitors are the notify(), notifyAll(), and the wait();
Reentrant Locks
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Counter{
private int count = 0;
private Lock lock = new ReentrantLock();
//Increment the counter
public void increment(){
lock.lock();
try{
count++;
System.out.println(Thread.currentThread().getName()+ " counter incremented to " + count);
} finally{
lock.unlock();
}
}
public int getCount(){
return count;
}
}
import java.util.concurrent.locks.ReentrantLock;
public class CounterWithReentrantLock{
private int count = 0;
private final ReentrantLock = new ReentrantLock();
public void increment(){
lock.lock();
try{
count++;
System.out.println(Thread.currentThread().getName() + " counter incremented to: " + count);
} finally{
lock.unlock();
}
}
public int getCount(){
return count;
}
}
class ReentrantLockExample{
public static void main(String[] args){
Counter counter = new Counter();
CounterWithReentrantLock reentrantCounter = new CounterWithReentrantLock();
Runnable task1 = () -> {
for (int i=0; i<10; i++){
counter.increment();
reentrantCounter.increment();
}
};
Thread thread1 = new Thread(task1, "Thread-1");
Thread thread2 = new Thread(task1, "Thread-2");
thread1.start();
thread2.start();
try{
thread1.join();
thread2.join();
} catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("Final count for counter: " + counter.getCount());
System.out.println("Final count for counter: " + reentrantCounter.getCounter());
}
}