0% found this document useful (0 votes)
4 views

Concurrency Test Questions

Uploaded by

nerdyall51
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Concurrency Test Questions

Uploaded by

nerdyall51
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

DEPARTMENT OF COMPUTER SCIENCES

FIRST SEMESTER 2023/2024 SESSION DECEMBER 2023


CSC302 – TEST 1

Time Allowed: 20 minutes

1
a
Discuss three (3) thread-safety issues in concurrent programs that developers
should be aware of.

b
What is the difference when lock is applied to an instance method and when lock is
applied to a static method?

c
Use the program listing below to answer the following:

i
Identify the shared resource in the code listing

ii
What is the function of the method newCachedThreadPool() in the listing and how
different is the method from newFixedThreadPool()?

iii
Do you think the code will yield desirable output? Justify your response.

iv
Use Java lock interface to resolve the possible conflict in the code listing.

v
Use synchronized keyword to resolve the possible conflict in the code listing.

vi
Use semaphore to control the number of threads that access the shared resource.
import java.util.concurrent.*;
public class Exercise1 {
private static Account acc = new Account();
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) { executor.execute(new AddMoney()); }
executor.shutdown();
while (!executor.isTerminated()) {
} System.out.println("What is balance ? " +acc.getBalance()); }
private static class AddMoney implements Runnable {
public void run() {
acc.deposit(1);
} }
private static class Account {
private int balance = 0;
public int getBalance() { return balance;
}
public void deposit(int amount) {
int newBalance = balance + amount;
try {
Thread.sleep(10);
}
catch (InterruptedException ex) { }
balance = newBalance;
} }}

You might also like