Search in sources :

Example 96 with ThreadPoolExecutor

use of java.util.concurrent.ThreadPoolExecutor in project android-priority-jobqueue by path.

the class MultiThreadTest method testMultiThreaded.

@Test
public void testMultiThreaded() throws Exception {
    multiThreadedJobCounter = new AtomicInteger(0);
    final JobManager jobManager = createJobManager(new Configuration.Builder(Robolectric.application).loadFactor(3).maxConsumerCount(10));
    int limit = 200;
    ExecutorService executor = new ThreadPoolExecutor(20, 20, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(limit));
    Collection<Future<?>> futures = new LinkedList<Future<?>>();
    for (int i = 0; i < limit; i++) {
        final int id = i;
        futures.add(executor.submit(new Runnable() {

            @Override
            public void run() {
                final boolean persistent = Math.round(Math.random()) % 2 == 0;
                boolean requiresNetwork = Math.round(Math.random()) % 2 == 0;
                int priority = (int) (Math.round(Math.random()) % 10);
                multiThreadedJobCounter.incrementAndGet();
                jobManager.addJob(new DummyJobForMultiThread(id, new Params(priority).setRequiresNetwork(requiresNetwork).setPersistent(persistent)));
            }
        }));
    }
    for (Future<?> future : futures) {
        future.get();
    }
    Log.d("TAG", "added all jobs");
    //wait until all jobs are added
    long start = System.nanoTime();
    //20 seconds
    long timeLimit = JobManager.NS_PER_MS * 20000;
    while (System.nanoTime() - start < timeLimit && multiThreadedJobCounter.get() != 0) {
        Thread.sleep(1000);
    }
    Log.d("TAG", "did we reach timeout? " + (System.nanoTime() - start >= timeLimit));
    MatcherAssert.assertThat("jobmanager count should be 0", jobManager.count(), equalTo(0));
    MatcherAssert.assertThat("multiThreadedJobCounter should be 0", multiThreadedJobCounter.get(), equalTo(0));
}
Also used : Configuration(com.path.android.jobqueue.config.Configuration) Params(com.path.android.jobqueue.Params) JobManager(com.path.android.jobqueue.JobManager) LinkedList(java.util.LinkedList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) Test(org.junit.Test)

Example 97 with ThreadPoolExecutor

use of java.util.concurrent.ThreadPoolExecutor in project realm-java by realm.

the class SyncUser method loginAsync.

/**
     * Logs in the user to the Realm Object Server. A logged in user is required to be able to create a
     * {@link SyncConfiguration}.
     *
     * @param credentials credentials to use.
     * @param authenticationUrl server that the user is authenticated against.
     * @param callback callback when login has completed or failed. The callback will always happen on the same thread
     *                 as this this method is called on.
     * @throws IllegalArgumentException if not on a Looper thread.
     */
public static RealmAsyncTask loginAsync(final SyncCredentials credentials, final String authenticationUrl, final Callback callback) {
    if (Looper.myLooper() == null) {
        throw new IllegalStateException("Asynchronous login is only possible from looper threads.");
    }
    final Handler handler = new Handler(Looper.myLooper());
    ThreadPoolExecutor networkPoolExecutor = SyncManager.NETWORK_POOL_EXECUTOR;
    Future<?> authenticateRequest = networkPoolExecutor.submit(new Runnable() {

        @Override
        public void run() {
            try {
                SyncUser user = login(credentials, authenticationUrl);
                postSuccess(user);
            } catch (ObjectServerError e) {
                postError(e);
            }
        }

        private void postError(final ObjectServerError error) {
            if (callback != null) {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            callback.onError(error);
                        } catch (Exception e) {
                            RealmLog.info("onError has thrown an exception but is ignoring it: %s", Util.getStackTrace(e));
                        }
                    }
                });
            }
        }

        private void postSuccess(final SyncUser user) {
            if (callback != null) {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        callback.onSuccess(user);
                    }
                });
            }
        }
    });
    return new RealmAsyncTaskImpl(authenticateRequest, networkPoolExecutor);
}
Also used : RealmAsyncTaskImpl(io.realm.internal.async.RealmAsyncTaskImpl) Handler(android.os.Handler) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) MalformedURLException(java.net.MalformedURLException)

Example 98 with ThreadPoolExecutor

use of java.util.concurrent.ThreadPoolExecutor in project realm-java by realm.

the class SyncUser method logout.

/**
     * Logs out the user from the Realm Object Server. Once the Object Server has confirmed the logout any registered
     * {@link AuthenticationListener} will be notified and user credentials will be deleted from this device.
     *
     * @throws IllegalStateException if any Realms owned by this user is still open. They should be closed before
     *         logging out.
     */
/* FIXME: Add this back to the javadoc when enable SyncConfiguration.Builder#deleteRealmOnLogout()
     <p>
     Any Realms owned by the user will be deleted if {@link SyncConfiguration.Builder#deleteRealmOnLogout()} is
     also set.
     */
public void logout() {
    // Acquire lock to prevent users creating new instances
    synchronized (Realm.class) {
        if (!syncUser.isLoggedIn()) {
            // Already local/global logout status
            return;
        }
        // Ensure that we can log out. If any Realm file is still open we should abort before doing anything
        // else.
        Collection<SyncSession> sessions = syncUser.getSessions();
        for (SyncSession session : sessions) {
            SyncConfiguration config = session.getConfiguration();
            if (Realm.getGlobalInstanceCount(config) > 0) {
                throw new IllegalStateException("A Realm controlled by this user is still open. Close all Realms " + "before logging out: " + config.getPath());
            }
        }
        SyncManager.getUserStore().remove(syncUser.getIdentity());
        // Delete all Realms if needed.
        for (ObjectServerUser.AccessDescription desc : syncUser.getRealms()) {
            // disabled. Make sure this works for Realm opened in the client thread/other processes.
            if (desc.deleteOnLogout) {
                File realmFile = new File(desc.localPath);
                if (realmFile.exists() && !Util.deleteRealm(desc.localPath, realmFile.getParentFile(), realmFile.getName())) {
                    RealmLog.error("Could not delete Realm when user logged out: " + desc.localPath);
                }
            }
        }
        // Remove all local tokens, preventing further connections.
        final Token userToken = syncUser.getUserToken();
        syncUser.clearTokens();
        syncUser.localLogout();
        // Finally revoke server token. The local user is logged out in any case.
        final AuthenticationServer server = SyncManager.getAuthServer();
        ThreadPoolExecutor networkPoolExecutor = SyncManager.NETWORK_POOL_EXECUTOR;
        networkPoolExecutor.submit(new ExponentialBackoffTask<LogoutResponse>() {

            @Override
            protected LogoutResponse execute() {
                return server.logout(userToken, syncUser.getAuthenticationUrl());
            }

            @Override
            protected void onSuccess(LogoutResponse response) {
                SyncManager.notifyUserLoggedOut(SyncUser.this);
            }

            @Override
            protected void onError(LogoutResponse response) {
                RealmLog.error("Failed to log user out.\n" + response.getError().toString());
            }
        });
    }
}
Also used : LogoutResponse(io.realm.internal.network.LogoutResponse) Token(io.realm.internal.objectserver.Token) AuthenticationServer(io.realm.internal.network.AuthenticationServer) ObjectServerUser(io.realm.internal.objectserver.ObjectServerUser) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) File(java.io.File)

Example 99 with ThreadPoolExecutor

use of java.util.concurrent.ThreadPoolExecutor in project reflections by ronmamo.

the class Reflections method scan.

//
protected void scan() {
    if (configuration.getUrls() == null || configuration.getUrls().isEmpty()) {
        if (log != null)
            log.warn("given scan urls are empty. set urls in the configuration");
        return;
    }
    if (log != null && log.isDebugEnabled()) {
        log.debug("going to scan these urls:\n" + Joiner.on("\n").join(configuration.getUrls()));
    }
    long time = System.currentTimeMillis();
    int scannedUrls = 0;
    ExecutorService executorService = configuration.getExecutorService();
    List<Future<?>> futures = Lists.newArrayList();
    for (final URL url : configuration.getUrls()) {
        try {
            if (executorService != null) {
                futures.add(executorService.submit(new Runnable() {

                    public void run() {
                        if (log != null && log.isDebugEnabled())
                            log.debug("[" + Thread.currentThread().toString() + "] scanning " + url);
                        scan(url);
                    }
                }));
            } else {
                scan(url);
            }
            scannedUrls++;
        } catch (ReflectionsException e) {
            if (log != null && log.isWarnEnabled())
                log.warn("could not create Vfs.Dir from url. ignoring the exception and continuing", e);
        }
    }
    //todo use CompletionService
    if (executorService != null) {
        for (Future future : futures) {
            try {
                future.get();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    time = System.currentTimeMillis() - time;
    //gracefully shutdown the parallel scanner executor service.
    if (executorService != null) {
        executorService.shutdown();
    }
    if (log != null) {
        int keys = 0;
        int values = 0;
        for (String index : store.keySet()) {
            keys += store.get(index).keySet().size();
            values += store.get(index).size();
        }
        log.info(format("Reflections took %d ms to scan %d urls, producing %d keys and %d values %s", time, scannedUrls, keys, values, executorService != null && executorService instanceof ThreadPoolExecutor ? format("[using %d cores]", ((ThreadPoolExecutor) executorService).getMaximumPoolSize()) : ""));
    }
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) URL(java.net.URL)

Example 100 with ThreadPoolExecutor

use of java.util.concurrent.ThreadPoolExecutor in project spring-framework by spring-projects.

the class ThreadPoolExecutorFactoryBean method initializeExecutor.

@Override
protected ExecutorService initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
    BlockingQueue<Runnable> queue = createQueue(this.queueCapacity);
    ThreadPoolExecutor executor = createExecutor(this.corePoolSize, this.maxPoolSize, this.keepAliveSeconds, queue, threadFactory, rejectedExecutionHandler);
    if (this.allowCoreThreadTimeOut) {
        executor.allowCoreThreadTimeOut(true);
    }
    // Wrap executor with an unconfigurable decorator.
    this.exposedExecutor = (this.exposeUnconfigurableExecutor ? Executors.unconfigurableExecutorService(executor) : executor);
    return executor;
}
Also used : ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Aggregations

ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)397 Test (org.junit.Test)79 ExecutorService (java.util.concurrent.ExecutorService)74 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)60 ThreadFactory (java.util.concurrent.ThreadFactory)38 ArrayList (java.util.ArrayList)34 IOException (java.io.IOException)33 ScheduledThreadPoolExecutor (java.util.concurrent.ScheduledThreadPoolExecutor)30 SynchronousQueue (java.util.concurrent.SynchronousQueue)29 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)23 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)23 RejectedExecutionHandler (java.util.concurrent.RejectedExecutionHandler)22 ExecutionException (java.util.concurrent.ExecutionException)21 Future (java.util.concurrent.Future)20 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)18 CountDownLatch (java.util.concurrent.CountDownLatch)18 Test (org.testng.annotations.Test)18 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)16 SizedScheduledExecutorService (org.apache.camel.util.concurrent.SizedScheduledExecutorService)16 HashMap (java.util.HashMap)14