Q. Given the following code, Client
|
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 |
package com.homeassignment.task5; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.LockSupport; public class Client { private AtomicInteger requestCount = new AtomicInteger(0); private AtomicInteger processedCount = new AtomicInteger(0); private Service service = null; public static void main(String[] args) { new Client().execute(); } private void execute() { service = new ServiceImpl(); int concurrentUsers = 25; int requestsPerUser = 10; final ExecutorService executorService = Executors.newFixedThreadPool(concurrentUsers, new ThreadFactory() { private AtomicInteger threadCnt = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { final Thread thread = new Thread(r, "Thread " + threadCnt.incrementAndGet()); thread.setDaemon(true); return thread; } }); for (int i = 1; i <= concurrentUsers; i++) { executorService.submit(new Runnable() { @Override public void run() { for (int j = 1; j <= requestsPerUser; j++) { service.process("Request-no-" + requestCount.incrementAndGet()); //invoking a service processedCount.incrementAndGet(); } } }); } while (processedCount.get() < requestCount.get()) { LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(20)); } executorService.shutdown(); } } |
Service interface & implementation
|
1 2 3 4 5 6 7 |
package com.homeassignment.task5; public interface Service { void process(String requestId); } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.homeassignment.task5; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; public class ServiceImpl implements Service { @Override public void process(final String requestId) { System.out.println("Started processing = " + requestId); // emulating actual processing LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(2000)); //XXX expensive call to a legacy system System.out.println("Finished processing = " + requestId); } } |
the line “XXX expensive call to a legacy system” in the “ServiceImpl” is an external call to a legacy system, which breaks when more than 5 concurrent…