Search in sources :

Example 1 with ForkJoinTask

use of java.util.concurrent.ForkJoinTask in project hibernate-orm by hibernate.

the class CorrectnessTestCase method test.

@Test
public void test() throws Exception {
    ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
    Map<Integer, List<Log<String>>> allFamilyNames = new HashMap<>();
    Map<Integer, List<Log<Set<String>>>> allFamilyMembers = new HashMap<>();
    running = true;
    List<Future<Void>> futures = new ArrayList<>();
    for (int node = 0; node < NUM_NODES; ++node) {
        final int NODE = node;
        for (int i = 0; i < NUM_THREADS_PER_NODE; ++i) {
            final int I = i;
            futures.add(exec.submit(() -> {
                Thread.currentThread().setName("Node" + (char) ('A' + NODE) + "-thread-" + I);
                threadNode.set(NODE);
                while (running) {
                    Operation operation;
                    if (familyIds.size() < NUM_FAMILIES) {
                        operation = new InsertFamily(ThreadLocalRandom.current().nextInt(5) == 0);
                    } else {
                        operation = getOperation();
                    }
                    try {
                        operation.run();
                    } catch (Exception e) {
                        // ignore exceptions from optimistic failures and induced exceptions
                        if (hasCause(e, InducedException.class)) {
                            continue;
                        } else if (Stream.of(EXPECTED).anyMatch(exceptions -> matches(e, exceptions))) {
                            continue;
                        }
                        exceptions.add(e);
                        log.error("Failed " + operation.getClass().getName(), e);
                    }
                }
                synchronized (allFamilyNames) {
                    for (Map.Entry<Integer, List<Log<String>>> entry : familyNames.get().entrySet()) {
                        List<Log<String>> list = allFamilyNames.get(entry.getKey());
                        if (list == null)
                            allFamilyNames.put(entry.getKey(), list = new ArrayList<>());
                        list.addAll(entry.getValue());
                    }
                    for (Map.Entry<Integer, List<Log<Set<String>>>> entry : familyMembers.get().entrySet()) {
                        List<Log<Set<String>>> list = allFamilyMembers.get(entry.getKey());
                        if (list == null)
                            allFamilyMembers.put(entry.getKey(), list = new ArrayList<>());
                        list.addAll(entry.getValue());
                    }
                }
                return null;
            }));
        }
    }
    Exception failure = exceptions.poll(EXECUTION_TIME, TimeUnit.MILLISECONDS);
    if (failure != null)
        exceptions.addFirst(failure);
    running = false;
    exec.shutdown();
    if (!exec.awaitTermination(1000, TimeUnit.SECONDS))
        throw new IllegalStateException();
    for (Future<Void> f : futures) {
        // check for exceptions
        f.get();
    }
    checkForEmptyPendingPuts();
    log.infof("Generated %d timestamps%n", timestampGenerator.get());
    AtomicInteger created = new AtomicInteger();
    AtomicInteger removed = new AtomicInteger();
    ForkJoinPool threadPool = ForkJoinPool.commonPool();
    ArrayList<ForkJoinTask<?>> tasks = new ArrayList<>();
    for (Map.Entry<Integer, List<Log<String>>> entry : allFamilyNames.entrySet()) {
        tasks.add(threadPool.submit(() -> {
            int familyId = entry.getKey();
            List<Log<String>> list = entry.getValue();
            created.incrementAndGet();
            NavigableMap<Integer, List<Log<String>>> logByTime = getWritesAtTime(list);
            checkCorrectness("family_name-" + familyId + "-", list, logByTime);
            if (list.stream().anyMatch(l -> l.type == LogType.WRITE && l.getValue() == null)) {
                removed.incrementAndGet();
            }
        }));
    }
    for (Map.Entry<Integer, List<Log<Set<String>>>> entry : allFamilyMembers.entrySet()) {
        tasks.add(threadPool.submit(() -> {
            int familyId = entry.getKey();
            List<Log<Set<String>>> list = entry.getValue();
            NavigableMap<Integer, List<Log<Set<String>>>> logByTime = getWritesAtTime(list);
            checkCorrectness("family_members-" + familyId + "-", list, logByTime);
        }));
    }
    for (ForkJoinTask<?> task : tasks) {
        // with heavy logging this may have trouble to complete
        task.get(30, TimeUnit.SECONDS);
    }
    if (!exceptions.isEmpty()) {
        for (Exception e : exceptions) {
            log.error("Test failure", e);
        }
        throw new IllegalStateException("There were " + exceptions.size() + " exceptions");
    }
    log.infof("Created %d families, removed %d%n", created.get(), removed.get());
}
Also used : Arrays(java.util.Arrays) ConfigurationBuilder(org.infinispan.configuration.cache.ConfigurationBuilder) Transaction(org.hibernate.Transaction) Future(java.util.concurrent.Future) PessimisticLockException(org.hibernate.PessimisticLockException) PersistentClass(org.hibernate.mapping.PersistentClass) Map(java.util.Map) StaleStateException(org.hibernate.StaleStateException) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) SessionFactory(org.hibernate.SessionFactory) Set(java.util.Set) Category(org.junit.experimental.categories.Category) Executors(java.util.concurrent.Executors) InvocationTargetException(java.lang.reflect.InvocationTargetException) InterceptorConfiguration(org.infinispan.configuration.cache.InterceptorConfiguration) Stream(java.util.stream.Stream) AfterClassOnce(org.hibernate.testing.AfterClassOnce) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) TestingJtaPlatformImpl(org.hibernate.testing.jta.TestingJtaPlatformImpl) InfinispanRegionFactory(org.hibernate.cache.infinispan.InfinispanRegionFactory) H2Dialect(org.hibernate.dialect.H2Dialect) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException) TestResourceTracker(org.infinispan.test.fwk.TestResourceTracker) RunWith(org.junit.runner.RunWith) SimpleDateFormat(java.text.SimpleDateFormat) Session(org.hibernate.Session) Metadata(org.hibernate.boot.Metadata) ArrayList(java.util.ArrayList) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) BiConsumer(java.util.function.BiConsumer) JtaTransactionCoordinatorBuilderImpl(org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl) Environment(org.hibernate.cfg.Environment) Family(org.hibernate.test.cache.infinispan.stress.entities.Family) Properties(java.util.Properties) Files(java.nio.file.Files) BlockingDeque(java.util.concurrent.BlockingDeque) BufferedWriter(java.io.BufferedWriter) OptimisticLockException(javax.persistence.OptimisticLockException) RollbackCommand(org.infinispan.commands.tx.RollbackCommand) IOException(java.io.IOException) Test(org.junit.Test) TestInfinispanRegionFactory(org.hibernate.test.cache.infinispan.util.TestInfinispanRegionFactory) Field(java.lang.reflect.Field) File(java.io.File) TreeMap(java.util.TreeMap) JdbcResourceLocalTransactionCoordinatorBuilderImpl(org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl) ForkJoinPool(java.util.concurrent.ForkJoinPool) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) InfinispanMessageLogger(org.hibernate.cache.infinispan.util.InfinispanMessageLogger) Date(java.util.Date) TransactionStatus(org.hibernate.resource.transaction.spi.TransactionStatus) Person(org.hibernate.test.cache.infinispan.stress.entities.Person) JtaAwareConnectionProviderImpl(org.hibernate.testing.jta.JtaAwareConnectionProviderImpl) InvocationContext(org.infinispan.context.InvocationContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AccessType(org.hibernate.cache.spi.access.AccessType) Method(java.lang.reflect.Method) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Parameterized(org.junit.runners.Parameterized) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) StaleObjectStateException(org.hibernate.StaleObjectStateException) Collection(org.hibernate.mapping.Collection) NavigableMap(java.util.NavigableMap) Collectors(java.util.stream.Collectors) TransactionException(org.hibernate.TransactionException) MetadataSources(org.hibernate.boot.MetadataSources) List(java.util.List) PersistenceException(javax.persistence.PersistenceException) Address(org.hibernate.test.cache.infinispan.stress.entities.Address) PutFromLoadValidator(org.hibernate.cache.infinispan.access.PutFromLoadValidator) TimeoutException(org.infinispan.util.concurrent.TimeoutException) Restrictions(org.hibernate.criterion.Restrictions) RootClass(org.hibernate.mapping.RootClass) HashMap(java.util.HashMap) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) ConcurrentMap(java.util.concurrent.ConcurrentMap) RegionAccessStrategy(org.hibernate.cache.spi.access.RegionAccessStrategy) HashSet(java.util.HashSet) RollbackException(javax.transaction.RollbackException) LinkedList(java.util.LinkedList) ExecutorService(java.util.concurrent.ExecutorService) ForkJoinTask(java.util.concurrent.ForkJoinTask) LockMode(org.hibernate.LockMode) Iterator(java.util.Iterator) CustomParameterized(org.hibernate.testing.junit4.CustomParameterized) NoJtaPlatform(org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform) CommitCommand(org.infinispan.commands.tx.CommitCommand) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) CacheMode(org.infinispan.configuration.cache.CacheMode) BaseCustomInterceptor(org.infinispan.interceptors.base.BaseCustomInterceptor) Ignore(org.junit.Ignore) BeforeClassOnce(org.hibernate.testing.BeforeClassOnce) VisitableCommand(org.infinispan.commands.VisitableCommand) Comparator(java.util.Comparator) TransactionManager(javax.transaction.TransactionManager) InvalidationCacheAccessDelegate(org.hibernate.cache.infinispan.access.InvalidationCacheAccessDelegate) RemoteException(org.infinispan.remoting.RemoteException) Collections(java.util.Collections) Set(java.util.Set) HashSet(java.util.HashSet) NavigableMap(java.util.NavigableMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ForkJoinTask(java.util.concurrent.ForkJoinTask) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) PessimisticLockException(org.hibernate.PessimisticLockException) StaleStateException(org.hibernate.StaleStateException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException) OptimisticLockException(javax.persistence.OptimisticLockException) IOException(java.io.IOException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) StaleObjectStateException(org.hibernate.StaleObjectStateException) TransactionException(org.hibernate.TransactionException) PersistenceException(javax.persistence.PersistenceException) TimeoutException(org.infinispan.util.concurrent.TimeoutException) RollbackException(javax.transaction.RollbackException) RemoteException(org.infinispan.remoting.RemoteException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) Map(java.util.Map) TreeMap(java.util.TreeMap) NavigableMap(java.util.NavigableMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) ForkJoinPool(java.util.concurrent.ForkJoinPool) Test(org.junit.Test)

Example 2 with ForkJoinTask

use of java.util.concurrent.ForkJoinTask in project buck by facebook.

the class TargetGraphHashing method hashTargetGraph.

/**
   * Given a {@link TargetGraph} and any number of root nodes to traverse,
   * returns a map of {@code (BuildTarget, HashCode)} pairs for all root
   * build targets and their dependencies.
   */
public ImmutableMap<BuildTarget, HashCode> hashTargetGraph() throws CycleException {
    try (SimplePerfEvent.Scope scope = SimplePerfEvent.scope(eventBus, PerfEventId.of("ShowTargetHashes"))) {
        AcyclicDepthFirstPostOrderTraversal<TargetNode<?, ?>> traversal = new AcyclicDepthFirstPostOrderTraversal<>(node -> targetGraph.getAll(node.getDeps()).iterator());
        final Map<BuildTarget, ForkJoinTask<HashCode>> buildTargetHashes = new HashMap<>();
        Queue<ForkJoinTask<HashCode>> tasksToSchedule = new ArrayDeque<>();
        // Start all the node tasks, bottom up
        for (final TargetNode<?, ?> node : traversal.traverse(roots)) {
            HashNodeTask task = new HashNodeTask(node, buildTargetHashes);
            buildTargetHashes.put(node.getBuildTarget(), task);
            tasksToSchedule.add(task);
        }
        // Execute tasks in parallel
        ForkJoinPool pool = new ForkJoinPool(numThreads);
        for (ForkJoinTask<HashCode> task : tasksToSchedule) {
            pool.execute(task);
        }
        // Wait for all scheduled tasks to complete
        return ImmutableMap.copyOf(Maps.transformEntries(buildTargetHashes, (key, value) -> value.join()));
    }
}
Also used : BuckEventBus(com.facebook.buck.event.BuckEventBus) PerfEventId(com.facebook.buck.event.PerfEventId) RecursiveTask(java.util.concurrent.RecursiveTask) SimplePerfEvent(com.facebook.buck.event.SimplePerfEvent) Hashing(com.google.common.hash.Hashing) HashMap(java.util.HashMap) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) Map(java.util.Map) AcyclicDepthFirstPostOrderTraversal(com.facebook.buck.graph.AcyclicDepthFirstPostOrderTraversal) CycleException(com.facebook.buck.graph.AcyclicDepthFirstPostOrderTraversal.CycleException) Hasher(com.google.common.hash.Hasher) StringHashing(com.facebook.buck.hashing.StringHashing) Path(java.nio.file.Path) FileHashLoader(com.facebook.buck.hashing.FileHashLoader) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) Logger(com.facebook.buck.log.Logger) ForkJoinTask(java.util.concurrent.ForkJoinTask) ImmutableMap(com.google.common.collect.ImmutableMap) HashCode(com.google.common.hash.HashCode) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) BuildTarget(com.facebook.buck.model.BuildTarget) Maps(com.google.common.collect.Maps) ForkJoinPool(java.util.concurrent.ForkJoinPool) Preconditions(com.google.common.base.Preconditions) Queue(java.util.Queue) ArrayDeque(java.util.ArrayDeque) HashMap(java.util.HashMap) ForkJoinTask(java.util.concurrent.ForkJoinTask) ArrayDeque(java.util.ArrayDeque) HashCode(com.google.common.hash.HashCode) BuildTarget(com.facebook.buck.model.BuildTarget) AcyclicDepthFirstPostOrderTraversal(com.facebook.buck.graph.AcyclicDepthFirstPostOrderTraversal) SimplePerfEvent(com.facebook.buck.event.SimplePerfEvent) ForkJoinPool(java.util.concurrent.ForkJoinPool)

Aggregations

IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 ForkJoinPool (java.util.concurrent.ForkJoinPool)2 ForkJoinTask (java.util.concurrent.ForkJoinTask)2 BuckEventBus (com.facebook.buck.event.BuckEventBus)1 PerfEventId (com.facebook.buck.event.PerfEventId)1 SimplePerfEvent (com.facebook.buck.event.SimplePerfEvent)1 AcyclicDepthFirstPostOrderTraversal (com.facebook.buck.graph.AcyclicDepthFirstPostOrderTraversal)1 CycleException (com.facebook.buck.graph.AcyclicDepthFirstPostOrderTraversal.CycleException)1 FileHashLoader (com.facebook.buck.hashing.FileHashLoader)1 StringHashing (com.facebook.buck.hashing.StringHashing)1 ProjectFilesystem (com.facebook.buck.io.ProjectFilesystem)1 Logger (com.facebook.buck.log.Logger)1 BuildTarget (com.facebook.buck.model.BuildTarget)1 HumanReadableException (com.facebook.buck.util.HumanReadableException)1 Preconditions (com.google.common.base.Preconditions)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 ImmutableSortedSet (com.google.common.collect.ImmutableSortedSet)1 Maps (com.google.common.collect.Maps)1