Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- import java.util.function.Supplier;
- public class Main {
- public static abstract class AbstractAdder {
- long res = 0;
- public void add(String toAdd) {
- runWithSync(() -> res += 1);
- }
- protected abstract void runWithSync(Supplier<?> dd);
- }
- public static class SyncAdder extends AbstractAdder{
- @Override
- protected void runWithSync(Supplier<?> dd) {
- synchronized (this) {
- dd.get();
- }
- }
- }
- public static class LockAdder extends AbstractAdder {
- private final Lock lock = new ReentrantLock();
- @Override
- protected void runWithSync(Supplier<?> dd) {
- lock.lock();
- try {
- dd.get();
- } finally {
- lock.unlock();
- }
- }
- }
- public static void main(String[] args) throws ExecutionException, InterruptedException {
- AbstractAdder sync = new SyncAdder();
- AbstractAdder lock = new LockAdder();
- runAdder(sync, "sync");
- runAdder(lock, "lock");
- System.out.println();
- runAdder(sync, "sync");
- runAdder(lock, "lock");
- System.out.println();
- runAdder(sync, "sync");
- runAdder(lock, "lock");
- System.out.println();
- runAdder(sync, "sync");
- runAdder(lock, "lock");
- System.out.println();
- runAdder(sync, "sync");
- runAdder(lock, "lock");
- System.out.println();
- runAdder(sync, "sync");
- runAdder(lock, "lock");
- System.out.println();
- runAdder(sync, "sync");
- runAdder(lock, "lock");
- }
- private static void runAdder(AbstractAdder adder, String name) throws ExecutionException, InterruptedException {
- int executors = 10;
- int adds = 10000000;
- long l = System.currentTimeMillis();
- ExecutorService executorService = Executors.newFixedThreadPool(executors);
- Future[] futures = new Future[executors];
- for (int i = 0; i < executors; i++) {
- Future<Void> future = executorService.submit(() -> {
- for (int j = 0; j < adds; j++) {
- adder.add("d");
- }
- return null;
- });
- futures[i] = future;
- }
- for (Future future : futures) {
- future.get();
- }
- executorService.shutdown();
- System.out.println(name + " spent " + (System.currentTimeMillis() - l) + " and got " + adder.res);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement