Search in sources :

Example 1 with ForkJoinPool

use of java.util.concurrent.ForkJoinPool in project hadoop by apache.

the class FSDirectory method updateCountForQuota.

/**
   * Update the count of each directory with quota in the namespace.
   * A directory's count is defined as the total number inodes in the tree
   * rooted at the directory.
   *
   * This is an update of existing state of the filesystem and does not
   * throw QuotaExceededException.
   */
void updateCountForQuota(int initThreads) {
    writeLock();
    try {
        int threads = (initThreads < 1) ? 1 : initThreads;
        LOG.info("Initializing quota with " + threads + " thread(s)");
        long start = Time.now();
        QuotaCounts counts = new QuotaCounts.Builder().build();
        ForkJoinPool p = new ForkJoinPool(threads);
        RecursiveAction task = new InitQuotaTask(getBlockStoragePolicySuite(), rootDir.getStoragePolicyID(), rootDir, counts);
        p.execute(task);
        task.join();
        p.shutdown();
        LOG.info("Quota initialization completed in " + (Time.now() - start) + " milliseconds\n" + counts);
    } finally {
        writeUnlock();
    }
}
Also used : RecursiveAction(java.util.concurrent.RecursiveAction) ForkJoinPool(java.util.concurrent.ForkJoinPool)

Example 2 with ForkJoinPool

use of java.util.concurrent.ForkJoinPool in project hbase by apache.

the class MultiThreadedClientExample method run.

@Override
public int run(String[] args) throws Exception {
    if (args.length < 1 || args.length > 2) {
        System.out.println("Usage: " + this.getClass().getName() + " tableName [num_operations]");
        return -1;
    }
    final TableName tableName = TableName.valueOf(args[0]);
    int numOperations = DEFAULT_NUM_OPERATIONS;
    // the second arg is the number of operations to send.
    if (args.length == 2) {
        numOperations = Integer.parseInt(args[1]);
    }
    // Threads for the client only.
    //
    // We don't want to mix hbase and business logic.
    //
    ExecutorService service = new ForkJoinPool(threads * 2);
    // Create two different connections showing how it's possible to
    // separate different types of requests onto different connections
    final Connection writeConnection = ConnectionFactory.createConnection(getConf(), service);
    final Connection readConnection = ConnectionFactory.createConnection(getConf(), service);
    // At this point the entire cache for the region locations is full.
    // Only do this if the number of regions in a table is easy to fit into memory.
    //
    // If you are interacting with more than 25k regions on a client then it's probably not good
    // to do this at all.
    warmUpConnectionCache(readConnection, tableName);
    warmUpConnectionCache(writeConnection, tableName);
    List<Future<Boolean>> futures = new ArrayList<>(numOperations);
    for (int i = 0; i < numOperations; i++) {
        double r = ThreadLocalRandom.current().nextDouble();
        Future<Boolean> f;
        // These callables are meant to represent real work done by your application.
        if (r < .30) {
            f = internalPool.submit(new WriteExampleCallable(writeConnection, tableName));
        } else if (r < .50) {
            f = internalPool.submit(new SingleWriteExampleCallable(writeConnection, tableName));
        } else {
            f = internalPool.submit(new ReadExampleCallable(writeConnection, tableName));
        }
        futures.add(f);
    }
    // Wait a long time for all the reads/writes to complete
    for (Future<Boolean> f : futures) {
        f.get(10, TimeUnit.MINUTES);
    }
    // Clean up after our selves for cleanliness
    internalPool.shutdownNow();
    service.shutdownNow();
    return 0;
}
Also used : Connection(org.apache.hadoop.hbase.client.Connection) ArrayList(java.util.ArrayList) TableName(org.apache.hadoop.hbase.TableName) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ForkJoinPool(java.util.concurrent.ForkJoinPool)

Example 3 with ForkJoinPool

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

the class IJProjectCleaner method clean.

@SuppressWarnings("serial")
public void clean(final BuckConfig buckConfig, final Path librariesXmlBase, final boolean runPostGenerationCleaner, final boolean removeOldLibraries) {
    if (!runPostGenerationCleaner && !removeOldLibraries) {
        return;
    }
    final Set<File> buckDirectories = new HashSet<>();
    buckDirectories.add(convertPathToFile(projectFilesystem.resolve(projectFilesystem.getBuckPaths().getBuckOut())));
    ArtifactCacheBuckConfig cacheBuckConfig = new ArtifactCacheBuckConfig(buckConfig);
    for (DirCacheEntry entry : cacheBuckConfig.getDirCacheEntries()) {
        buckDirectories.add(convertPathToFile(entry.getCacheDir()));
    }
    ForkJoinPool cleanExecutor = new ForkJoinPool(getParallelismLimit());
    try {
        cleanExecutor.invoke(new RecursiveAction() {

            @Override
            protected void compute() {
                List<RecursiveAction> topLevelTasks = new ArrayList<>(2);
                if (runPostGenerationCleaner) {
                    topLevelTasks.add(new CandidateFinderWithExclusions(convertPathToFile(projectFilesystem.resolve("")), IML_FILENAME_FILTER, buckDirectories));
                }
                topLevelTasks.add(new CandidateFinder(convertPathToFile(librariesXmlBase), XML_FILENAME_FILTER));
                invokeAll(topLevelTasks);
            }
        });
    } finally {
        cleanExecutor.shutdown();
        try {
            cleanExecutor.awaitTermination(EXECUTOR_SHUTDOWN_TIMEOUT, EXECUTOR_SHUTDOWN_TIME_UNIT);
        } catch (InterruptedException e) {
            Logger.get(IJProjectCleaner.class).warn("Timeout during executor shutdown.", e);
        }
    }
}
Also used : DirCacheEntry(com.facebook.buck.artifact_cache.DirCacheEntry) RecursiveAction(java.util.concurrent.RecursiveAction) ArtifactCacheBuckConfig(com.facebook.buck.artifact_cache.ArtifactCacheBuckConfig) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) HashSet(java.util.HashSet) ForkJoinPool(java.util.concurrent.ForkJoinPool)

Example 4 with ForkJoinPool

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

the class PythonLibraryDescriptionTest method versionedSrcs.

@Test
public void versionedSrcs() throws Exception {
    BuildTarget target = BuildTargetFactory.newInstance("//foo:lib");
    SourcePath matchedSource = new FakeSourcePath("foo/a.py");
    SourcePath unmatchedSource = new FakeSourcePath("foo/b.py");
    GenruleBuilder transitiveDepBuilder = GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:tdep")).setOut("out");
    VersionedAliasBuilder depBuilder = new VersionedAliasBuilder(BuildTargetFactory.newInstance("//:dep")).setVersions(ImmutableMap.of(Version.of("1.0"), transitiveDepBuilder.getTarget(), Version.of("2.0"), transitiveDepBuilder.getTarget()));
    AbstractNodeBuilder<?, ?, ?> builder = new PythonLibraryBuilder(target).setVersionedSrcs(VersionMatchedCollection.<SourceList>builder().add(ImmutableMap.of(depBuilder.getTarget(), Version.of("1.0")), SourceList.ofUnnamedSources(ImmutableSortedSet.of(matchedSource))).add(ImmutableMap.of(depBuilder.getTarget(), Version.of("2.0")), SourceList.ofUnnamedSources(ImmutableSortedSet.of(unmatchedSource))).build());
    TargetGraph targetGraph = VersionedTargetGraphBuilder.transform(new FixedVersionSelector(ImmutableMap.of(builder.getTarget(), ImmutableMap.of(depBuilder.getTarget(), Version.of("1.0")))), TargetGraphAndBuildTargets.of(TargetGraphFactory.newInstance(transitiveDepBuilder.build(), depBuilder.build(), builder.build()), ImmutableSet.of(builder.getTarget())), new ForkJoinPool()).getTargetGraph();
    BuildRuleResolver resolver = new BuildRuleResolver(targetGraph, new DefaultTargetNodeToBuildRuleTransformer());
    PythonLibrary library = (PythonLibrary) resolver.requireRule(builder.getTarget());
    assertThat(library.getPythonPackageComponents(PythonTestUtils.PYTHON_PLATFORM, CxxPlatformUtils.DEFAULT_PLATFORM).getModules().values(), Matchers.contains(matchedSource));
}
Also used : FakeSourcePath(com.facebook.buck.rules.FakeSourcePath) TargetGraph(com.facebook.buck.rules.TargetGraph) GenruleBuilder(com.facebook.buck.shell.GenruleBuilder) CxxGenruleBuilder(com.facebook.buck.cxx.CxxGenruleBuilder) FixedVersionSelector(com.facebook.buck.versions.FixedVersionSelector) BuildRuleResolver(com.facebook.buck.rules.BuildRuleResolver) VersionedAliasBuilder(com.facebook.buck.versions.VersionedAliasBuilder) SourcePath(com.facebook.buck.rules.SourcePath) FakeSourcePath(com.facebook.buck.rules.FakeSourcePath) DefaultBuildTargetSourcePath(com.facebook.buck.rules.DefaultBuildTargetSourcePath) BuildTarget(com.facebook.buck.model.BuildTarget) SourceList(com.facebook.buck.rules.coercer.SourceList) DefaultTargetNodeToBuildRuleTransformer(com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer) ForkJoinPool(java.util.concurrent.ForkJoinPool) Test(org.junit.Test)

Example 5 with ForkJoinPool

use of java.util.concurrent.ForkJoinPool 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)

Aggregations

ForkJoinPool (java.util.concurrent.ForkJoinPool)20 List (java.util.List)4 Test (org.junit.Test)4 File (java.io.File)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 Arrays (java.util.Arrays)3 Collections (java.util.Collections)3 Map (java.util.Map)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 Collectors (java.util.stream.Collectors)3 CxxGenruleBuilder (com.facebook.buck.cxx.CxxGenruleBuilder)2 BuildTarget (com.facebook.buck.model.BuildTarget)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 Serializable (java.io.Serializable)2 HashSet (java.util.HashSet)2 ExecutionException (java.util.concurrent.ExecutionException)2 ExecutorService (java.util.concurrent.ExecutorService)2 ForkJoinWorkerThreadFactory (java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory)2 ForkJoinWorkerThread (java.util.concurrent.ForkJoinWorkerThread)2