Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashMap;
- import java.util.Random;
- import java.util.Scanner;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.atomic.AtomicReference;
- public class Main {
- AtomicReference<HashMap<String, Integer>> accToAmount = new AtomicReference<>(new HashMap<>());
- boolean withdraw(String accountNumber, Integer amountToSubstract) {
- if (accToAmount.get().get(accountNumber) < amountToSubstract) {
- return false;
- }
- HashMap<String, Integer> currentMap, newMap;
- synchronized (this){
- currentMap = accToAmount.get();
- newMap = new HashMap<>(currentMap);
- newMap.put(accountNumber, currentMap.get(accountNumber) - amountToSubstract);
- accToAmount.set(newMap);
- };
- return true;
- }
- void add(String accountNumber, Integer amountToAdd) {
- HashMap<String, Integer> currentMap, newMap;
- synchronized (this){
- currentMap = accToAmount.get();
- newMap = new HashMap<>(currentMap);
- newMap.put(accountNumber, currentMap.get(accountNumber) - amountToAdd);
- accToAmount.set(newMap);
- };
- }
- public static void main(String[] args) {
- Main main = new Main();
- for (int i = 1; i <= 10; i++) {
- main.accToAmount.get().put("Account" + i, (int)1e6);
- }
- final int NUM_THREADS = 100;
- ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
- for (int i = 0; i < NUM_THREADS; i++) {
- executorService.execute(() -> {
- //main.withdraw("Account1", 100);
- Random random = new Random();
- int acNr = random.nextInt(10) + 1;
- for (int j = 0; j < 10; j++) {
- double op = random.nextDouble();
- int val = random.nextInt(1000) + 1;
- if (op >= 0.5) {
- boolean ok = main.withdraw("Account" + acNr, val);
- if (!ok) {
- System.err.println("failed withdraw");
- }
- } else {
- main.add("Account" + acNr, val);
- }
- }
- });
- }
- executorService.shutdown();
- for (int i = 1; i <= 10; i++) {
- System.out.println("Account" + i + ": " + main.accToAmount.get().get("Account" + i));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement