Example usage for java.lang Thread interrupted

List of usage examples for java.lang Thread interrupted

Introduction

In this page you can find the example usage for java.lang Thread interrupted.

Prototype

public static boolean interrupted() 

Source Link

Document

Tests whether the current thread has been interrupted.

Usage

From source file:com.github.michalbednarski.intentslab.browser.ComponentFetcher.java

@Override
Object getEntries(Context context) {
    PackageManager pm = context.getPackageManager();
    int requestedPackageInfoFlags = type | PackageManager.GET_DISABLED_COMPONENTS
            | (requireMetaDataSubstring != null ? PackageManager.GET_META_DATA : 0);

    boolean workAroundSmallBinderBuffer = false;
    List<PackageInfo> allPackages = null;
    try {/*from   ww  w .j  a  v  a 2s  .c  om*/
        allPackages = pm.getInstalledPackages(requestedPackageInfoFlags);
    } catch (Exception e) {
        Log.w(TAG, "Loading all apps at once failed, retrying separately", e);
    }

    if (allPackages == null || allPackages.isEmpty()) {
        workAroundSmallBinderBuffer = true;
        allPackages = pm.getInstalledPackages(0);
    }

    ArrayList<Category> selectedApps = new ArrayList<Category>();

    for (PackageInfo pack : allPackages) {
        // Filter out non-applications
        if (pack.applicationInfo == null) {
            continue;
        }

        // System app filter
        if ((((pack.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? APP_TYPE_SYSTEM : APP_TYPE_USER)
                & appType) == 0) {
            continue;
        }

        // Load component information separately if they were to big to send them all at once
        if (workAroundSmallBinderBuffer) {
            try {
                pack = pm.getPackageInfo(pack.packageName, requestedPackageInfoFlags);
            } catch (PackageManager.NameNotFoundException e) {
                Log.w(TAG, "getPackageInfo() thrown NameNotFoundException for " + pack.packageName, e);
                continue;
            }
        }

        // Scan components
        ArrayList<Component> selectedComponents = new ArrayList<Component>();

        if ((type & PackageManager.GET_ACTIVITIES) != 0) {
            scanComponents(pm, pack.activities, selectedComponents);
        }
        if ((type & PackageManager.GET_RECEIVERS) != 0) {
            scanComponents(pm, pack.receivers, selectedComponents);
        }
        if ((type & PackageManager.GET_SERVICES) != 0) {
            scanComponents(pm, pack.services, selectedComponents);
        }
        if ((type & PackageManager.GET_PROVIDERS) != 0) {
            scanComponents(pm, pack.providers, selectedComponents);
        }

        // Check if we filtered out all components and skip whole app if so
        if (selectedComponents.isEmpty()) {
            continue;
        }

        // Build and add app descriptor
        Category app = new Category();
        app.title = String.valueOf(pack.applicationInfo.loadLabel(pm));
        app.subtitle = pack.packageName;
        app.components = selectedComponents.toArray(new Component[selectedComponents.size()]);
        selectedApps.add(app);

        // Allow cancelling task
        if (Thread.interrupted()) {
            return null;
        }
    }
    return selectedApps.toArray(new Category[selectedApps.size()]);
}

From source file:uk.ac.horizon.ug.exploding.client.BackgroundThread.java

/** run method */
@Override/*from w  ww . jav  a  2 s .c om*/
public void run() {
    log("run()");
    mainloop: while (Thread.currentThread() == singleton) {
        try {
            boolean doLogin = false, doGetState = false, doPoll = false, doSendQueuedMessages = false;
            ClientState clientStateEvent = null;
            synchronized (BackgroundThread.class) {
                // recheck in sync block
                if (Thread.currentThread() != singleton)
                    break;
                // Synchronized!
                //Log.d(TAG, "Background action on state "+currentClientState);
                switch (currentClientState.getClientStatus()) {
                case CONFIGURING:
                    // no op
                    break;
                case CANCELLED_BY_USER:
                case ERROR_DOING_LOGIN:
                case ERROR_GETTING_STATE:
                case ERROR_IN_SERVER_URL:
                    Log.i(TAG, "Background thread give up on state " + currentClientState.getClientStatus());
                    break mainloop;
                case NEW:
                    // TODO log in
                    currentClientState.setClientStatus(ClientStatus.LOGGING_IN);
                    clientStateEvent = currentClientState.clone();
                    doLogin = true;
                    break;
                case GETTING_STATE:
                    doGetState = true;
                    break;
                case POLLING:
                case IDLE:
                case ERROR_AFTER_STATE: {
                    doSendQueuedMessages = true;
                    int pollInterval = POLL_INTERVAL_MS;
                    SharedPreferences preferences = getSharedPreferences();
                    if (preferences != null) {
                        try {
                            pollInterval = Integer
                                    .parseInt(preferences.getString("pollInterval", "" + pollInterval));
                        } catch (NumberFormatException e) {
                            Log.e(TAG, "Getting pollInterval", e);
                        }
                    }
                    if (System.currentTimeMillis() - lastPollTime > pollInterval) {
                        doPoll = true;
                    }
                }
                }
                // End Synchronized!
            }
            // unsync
            if (clientStateEvent != null)
                fireClientStateChanged(clientStateEvent);
            if (doLogin)
                doLogin();
            else if (doGetState)
                doGetState();
            else if (doPoll) {
                lastPollTime = System.currentTimeMillis();
                doPoll();
            } else if (doSendQueuedMessages) {
                client.waitOnQueuedMessages((int) THREAD_SLEEP_MS);
                doSendQueuedMessages();
            } else {
                try {
                    synchronized (Thread.currentThread()) {
                        Thread.currentThread().wait(THREAD_SLEEP_MS);
                    }
                } catch (InterruptedException ie) {
                    Log.d(TAG, "BackgroundThread interrtuped");
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception in background thread " + Thread.currentThread(), e);
            // TODO ERROR?
        }
    }
    log("done");
    Log.i(TAG, "Background thread " + Thread.currentThread() + " exiting (interrupted=" + Thread.interrupted()
            + ")");
}

From source file:com.googlecode.msidor.springframework.integration.channel.ConcurentOrderedMultiQueueChannel.java

/**
 * Try to find the eligible message./*from  www  . j  a v a  2  s. co m*/
 * Eligible means that message should not be locked by other thread or the lock has expired.
 * Message selection is made by round-robin algorithm.
 * This message should be called only when caller has an exclusive lock on object 
 *     
 * @return eligible message or null if no eligible message was found and all queues have been scanned
 */
private Message<?> findEligibleMessage() {

    Message<?> messageToReturn = null;

    //keep the initial queue ID in memory to know when all queues were scanned and to prevent the infinite looping
    Object initialQueueId = currentQueueId;
    boolean firstIteration = true;

    /* The end search conditions:
     * - thread was interupted
     * - eligible message was found 
     * - all queues have been scanned
     */

    while (!Thread.interrupted() && messageToReturn == null && initialQueueId != null
            && firstIteration == initialQueueId.equals(currentQueueId)) {

        firstIteration = false;

        //get current queue then find the next queue id on list and set it as the current queue id 
        List<Message<?>> messages = getCurrentQueue();

        if (messages != null) {
            for (Message<?> message : messages) {
                //get the execution ID for message
                Object executionId = getExecutionIdFromMessage(message);

                if (executionId != null) {
                    //check if execution ID is already locked
                    if (executionsLocks.containsKey(executionId)) {

                        //check if execution ID hasn't expired
                        if (System.currentTimeMillis()
                                - executionsLocks.get(executionId).longValue() < timeoutForExecutionLock) {
                            log.trace("Trying to pull message " + message + " but the Execution ID "
                                    + executionId + " is being held by other thread");
                        } else {
                            log.trace(executionId
                                    + " is being held by other thread but the lock is too old thus releasing the lock");
                            messageToReturn = message;
                        }
                    } else {
                        messageToReturn = message;
                    }

                    if (messageToReturn != null) {
                        //lock the execution ID 
                        lockExecutionId(message);
                        break;
                    }
                } else {
                    messageToReturn = message;
                    break;
                }
            }
        }

        if (messageToReturn != null) {
            //remove message from queue
            messages.remove(messageToReturn);
        }
    }

    return messageToReturn;
}

From source file:org.apache.gobblin.ingestion.google.webmaster.GoogleWebmasterDataFetcherImpl.java

/**
 * @return the size of all pages data set
 *//*from   w ww.  j a  va2  s .  c  o m*/
private int getPagesSize(final String startDate, final String endDate, final String country,
        final List<Dimension> requestedDimensions, final List<ApiDimensionFilter> apiDimensionFilters)
        throws IOException {
    final ExecutorService es = Executors.newCachedThreadPool(ExecutorsUtils
            .newDaemonThreadFactory(Optional.of(log), Optional.of(this.getClass().getSimpleName())));

    int startRow = 0;
    long groupSize = Math.max(1, Math.round(API_REQUESTS_PER_SECOND));
    List<Future<Integer>> results = new ArrayList<>((int) groupSize);

    while (true) {
        for (int i = 0; i < groupSize; ++i) {
            final int start = startRow;
            startRow += GoogleWebmasterClient.API_ROW_LIMIT;

            Future<Integer> submit = es.submit(new Callable<Integer>() {
                @Override
                public Integer call() {
                    log.info(String.format("Getting page size from %s...", start));
                    String interruptedMsg = String.format(
                            "Interrupted while trying to get the size of all pages for %s. Current start row is %d.",
                            country, start);
                    while (true) {
                        try {
                            LIMITER.acquirePermits(1);
                        } catch (InterruptedException e) {
                            log.error("RateBasedLimiter: " + interruptedMsg, e);
                            return -1;
                        }

                        if (Thread.interrupted()) {
                            log.error(interruptedMsg);
                            return -1;
                        }

                        try {
                            List<String> pages = _client.getPages(_siteProperty, startDate, endDate, country,
                                    GoogleWebmasterClient.API_ROW_LIMIT, requestedDimensions,
                                    apiDimensionFilters, start);
                            if (pages.size() < GoogleWebmasterClient.API_ROW_LIMIT) {
                                return pages.size() + start; //Figured out the size
                            } else {
                                return -1;
                            }
                        } catch (IOException e) {
                            log.info(String.format("Getting page size from %s failed. Retrying...", start));
                        }
                    }
                }
            });
            results.add(submit);
        }
        //Check the results group in order. The first non-negative count indicates the size of total pages.
        for (Future<Integer> result : results) {
            try {
                Integer integer = result.get(GET_PAGE_SIZE_TIME_OUT, TimeUnit.MINUTES);
                if (integer >= 0) {
                    es.shutdownNow();
                    return integer;
                }
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            } catch (TimeoutException e) {
                throw new RuntimeException(String.format(
                        "Exceeding the timeout of %d minutes while getting the total size of all pages.",
                        GET_PAGE_SIZE_TIME_OUT), e);
            }
        }
        results.clear();
    }
}

From source file:org.apache.hive.spark.client.SparkSubmitSparkClient.java

@Override
protected Future<Void> launchDriver(String isTesting, RpcServer rpcServer, String clientId) throws IOException {
    Callable<Void> runnable;

    String cmd = Joiner.on(" ").join(argv);
    LOG.info("Running client driver with argv: {}", cmd);
    ProcessBuilder pb = new ProcessBuilder("sh", "-c", cmd);

    // Prevent hive configurations from being visible in Spark.
    pb.environment().remove("HIVE_HOME");
    pb.environment().remove("HIVE_CONF_DIR");
    // Add credential provider password to the child process's environment
    // In case of Spark the credential provider location is provided in the jobConf when the job is submitted
    String password = getSparkJobCredentialProviderPassword();
    if (password != null) {
        pb.environment().put(Constants.HADOOP_CREDENTIAL_PASSWORD_ENVVAR, password);
    }/*from  ww  w.  jav a  2 s .  c o  m*/
    if (isTesting != null) {
        pb.environment().put("SPARK_TESTING", isTesting);
    }

    final Process child = pb.start();
    String threadName = Thread.currentThread().getName();
    final List<String> childErrorLog = Collections.synchronizedList(new ArrayList<String>());
    final LogRedirector.LogSourceCallback callback = () -> isAlive;

    LogRedirector.redirect("spark-submit-stdout-redir-" + threadName,
            new LogRedirector(child.getInputStream(), LOG, callback));
    LogRedirector.redirect("spark-submit-stderr-redir-" + threadName,
            new LogRedirector(child.getErrorStream(), LOG, childErrorLog, callback));

    runnable = () -> {
        try {
            int exitCode = child.waitFor();
            if (exitCode != 0) {
                List<String> errorMessages = new ArrayList<>();
                synchronized (childErrorLog) {
                    for (String line : childErrorLog) {
                        if (StringUtils.containsIgnoreCase(line, "Error")) {
                            errorMessages.add("\"" + line + "\"");
                        }
                    }
                }

                String errStr = errorMessages.isEmpty() ? "?" : Joiner.on(',').join(errorMessages);

                rpcServer.cancelClient(clientId, new RuntimeException("spark-submit process failed "
                        + "with exit code " + exitCode + " and error " + errStr));
            }
        } catch (InterruptedException ie) {
            LOG.warn(
                    "Thread waiting on the child process (spark-submit) is interrupted, killing the child process.");
            rpcServer.cancelClient(clientId,
                    "Thread waiting on the child process (spark-submit) is interrupted");
            Thread.interrupted();
            child.destroy();
        } catch (Exception e) {
            String errMsg = "Exception while waiting for child process (spark-submit)";
            LOG.warn(errMsg, e);
            rpcServer.cancelClient(clientId, errMsg);
        }
        return null;
    };

    FutureTask<Void> futureTask = new FutureTask<>(runnable);

    Thread driverThread = new Thread(futureTask);
    driverThread.setDaemon(true);
    driverThread.setName("SparkSubmitMonitor");
    driverThread.start();

    return futureTask;
}

From source file:com.btoddb.fastpersitentqueue.InMemorySegmentMgr.java

/**
 * pick segment and push events./*from w ww.  j  a v a 2s.c o m*/
 *
 * @param events
 */
public void push(Collection<FpqEntry> events) {
    if (shutdownInProgress) {
        throw new FpqException("FPQ has been shutdown or is in progress, cannot push events");
    }

    // calculate memory used by the list of entries
    long spaceRequired = 0;
    for (FpqEntry entry : events) {
        spaceRequired += entry.getMemorySize();
    }

    if (spaceRequired > maxSegmentSizeInBytes) {
        throw new FpqException(String.format(
                "the space required to push entries (%d) is greater than maximum segment size (%d) - increase segment size or reduce entry size",
                spaceRequired, maxSegmentSizeInBytes));
    }

    logger.debug("pushing {} event(s) totalling {} bytes", events.size(), spaceRequired);
    MemorySegment segment;
    while (true) {
        // grab the newest segment (last) and try to push to it.  we always push to the newest segment.
        // this is thread-safe because ConcurrentSkipListSet says so
        try {
            segment = segments.last();
        } catch (NoSuchElementException e) {
            logger.warn("no segments ready for pushing - not really a good thing");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
                // ignore
                Thread.interrupted();
            }
            continue;
        }

        // claim some room in this segment - if enough, then append entries and return
        // if not enough room in this segment, no attempt is made to push the partial batch and
        // this segment will be "push finished" regardless of how much room is available
        try {
            if (segment.push(events, spaceRequired)) {
                logger.debug("pushed {} events to segment {}", events.size(), segment.getId());
                numberOfEntries.addAndGet(events.size());
                return;
            } else {
                logger.debug(
                        "not enough room to push {} events to segment {} - skip to next segment (if there is one)",
                        events.size(), segment.getId());
            }
        }
        // only one time per segment will this exception be thrown.  if caught, signals
        // this thread should check if needed to be paged out to disk
        catch (FpqPushFinished e) {
            createNewSegment();
            synchronized (numberOfActiveSegments) {
                if (numberOfActiveSegments.get() > maxNumberOfActiveSegments) {
                    pageSegmentToDisk(segment);
                }
            }
            logger.debug("creating new segment - now {} active segments", numberOfActiveSegments.get());
        }
    }
}

From source file:gobblin.ingestion.google.webmaster.GoogleWebmasterDataFetcherImpl.java

private int getPagesSize(final String startDate, final String endDate, final String country,
        final List<Dimension> requestedDimensions, final List<ApiDimensionFilter> apiDimensionFilters)
        throws IOException {
    final ExecutorService es = Executors.newCachedThreadPool(ExecutorsUtils
            .newDaemonThreadFactory(Optional.of(log), Optional.of(this.getClass().getSimpleName())));

    int startRow = 0;
    long groupSize = Math.max(1, Math.round(API_REQUESTS_PER_SECOND));
    List<Future<Integer>> results = new ArrayList<>((int) groupSize);

    while (true) {
        for (int i = 0; i < groupSize; ++i) {
            startRow += GoogleWebmasterClient.API_ROW_LIMIT;
            final int start = startRow;
            final String interruptedMsg = String.format(
                    "Interrupted while trying to get the size of all pages for %s. Current start row is %d.",
                    country, start);/*from  www  .j a v a 2  s  .com*/

            Future<Integer> submit = es.submit(new Callable<Integer>() {
                @Override
                public Integer call() {
                    log.info(String.format("Getting page size from %s...", start));
                    while (true) {
                        try {
                            LIMITER.acquirePermits(1);
                        } catch (InterruptedException e) {
                            log.error("RateBasedLimiter: " + interruptedMsg, e);
                            return -1;
                        }

                        if (Thread.interrupted()) {
                            log.error(interruptedMsg);
                            return -1;
                        }

                        try {
                            List<String> pages = _client.getPages(_siteProperty, startDate, endDate, country,
                                    GoogleWebmasterClient.API_ROW_LIMIT, requestedDimensions,
                                    apiDimensionFilters, start);
                            if (pages.size() < GoogleWebmasterClient.API_ROW_LIMIT) {
                                return pages.size() + start; //Figured out the size
                            } else {
                                return -1;
                            }
                        } catch (IOException e) {
                            log.info(String.format("Getting page size from %s failed. Retrying...", start));
                        }
                    }
                }
            });
            results.add(submit);
        }
        //Check the results group in order. The first non-negative count indicates the size of total pages.
        for (Future<Integer> result : results) {
            try {
                Integer integer = result.get(GET_PAGE_SIZE_TIME_OUT, TimeUnit.MINUTES);
                if (integer >= 0) {
                    es.shutdownNow();
                    return integer;
                }
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            } catch (TimeoutException e) {
                throw new RuntimeException(String.format(
                        "Exceeding the timeout of %d minutes while getting the total size of all pages.",
                        GET_PAGE_SIZE_TIME_OUT), e);
            }
        }
        results.clear();
    }
}

From source file:fi.luontola.cqrshotel.framework.EventStoreContract.java

private static void repeatInParallel(int iterations, Runnable task, Runnable invariantChecker)
        throws Exception {
    final int PARALLELISM = 10;
    ExecutorService executor = Executors.newFixedThreadPool(PARALLELISM + 1);
    Future<?> checker;//from   ww  w  .  j av a2 s.c  om
    try {
        checker = executor.submit(() -> {
            while (!Thread.interrupted()) {
                invariantChecker.run();
                Thread.yield();
            }
        });
        List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < iterations; i++) {
            futures.add(executor.submit(task));
        }
        for (Future<?> future : futures) {
            // will throw ExecutionException if there was a problem
            future.get();
        }
    } finally {
        executor.shutdownNow();
        executor.awaitTermination(10, TimeUnit.SECONDS);
    }
    // will throw ExecutionException if there was a problem
    checker.get(10, TimeUnit.SECONDS);
}

From source file:com.z3r0byte.magistify.Fragments.AppointmentFragment.java

public void refresh() {
    if (refreshThread != null) {
        refreshThread.interrupt();//  w  w w. j a v  a 2  s . c o m
    }
    mSwipeRefreshLayout.setRefreshing(true);
    currentDay.setText(DateUtils.formatDate(selectedDate, "EEE dd MMM"));
    refreshThread = new Thread(new Runnable() {
        @Override
        public void run() {
            Magister magister = GlobalAccount.MAGISTER;
            if (magister != null && magister.isExpired()) {
                try {
                    magister.login();
                    GlobalAccount.MAGISTER = magister;
                } catch (IOException e) {
                    Log.e(TAG, "run: No connection during login", e);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listView.setVisibility(View.GONE);
                            errorView.setVisibility(View.VISIBLE);
                            errorView.setConfig(ErrorViewConfigs.NoConnectionConfig);
                            mSwipeRefreshLayout.setRefreshing(false);
                        }
                    });
                    return;
                }
            } else if (magister == null) {
                User user = new Gson().fromJson(configUtil.getString("User"), User.class);
                School school = new Gson().fromJson(configUtil.getString("School"), School.class);
                try {
                    GlobalAccount.MAGISTER = Magister.login(school, user.username, user.password);
                    magister = GlobalAccount.MAGISTER;
                } catch (IOException | ParseException | InvalidParameterException | NullPointerException e) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listView.setVisibility(View.GONE);
                            errorView.setVisibility(View.VISIBLE);
                            errorView.setConfig(ErrorViewConfigs.NoConnectionConfig);
                            mSwipeRefreshLayout.setRefreshing(false);
                        }
                    });
                    return;
                }
            }

            if (Thread.interrupted()) {
                return;
            }

            AppointmentHandler appointmentHandler = new AppointmentHandler(magister);
            try {
                Appointments = appointmentHandler.getAppointments(selectedDate, selectedDate);
            } catch (InterruptedIOException e) {
                e.printStackTrace();
                return;
            } catch (IOException e) {
                Appointments = null;
                Log.e(TAG, "run: No connection...", e);
            }

            if (Thread.interrupted() || getActivity() == null) {
                return;
            }

            if (Appointments != null && Appointments.length != 0) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mAppointmentsAdapter = new AppointmentsAdapter(getActivity(), Appointments);
                        listView.setAdapter(mAppointmentsAdapter);
                        listView.setVisibility(View.VISIBLE);
                        errorView.setVisibility(View.GONE);
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                });
            } else if (Appointments != null && Appointments.length < 1) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listView.setVisibility(View.GONE);
                        errorView.setVisibility(View.VISIBLE);
                        errorView.setConfig(ErrorViewConfigs.NoLessonConfig);
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                });
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listView.setVisibility(View.GONE);
                        errorView.setVisibility(View.VISIBLE);
                        errorView.setConfig(ErrorViewConfigs.NoConnectionConfig);
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                });
            }
        }
    });
    refreshThread.start();
}

From source file:org.apache.sqoop.mapreduce.db.netezza.NetezzaExternalTableExportMapper.java

@Override
public void run(Context context) throws IOException, InterruptedException {
    setup(context);// w  w  w.  java2s  . com
    initNetezzaExternalTableExport(context);
    if (extTableThread.isAlive()) {
        try {
            while (context.nextKeyValue()) {
                if (Thread.interrupted()) {
                    if (!extTableThread.isAlive()) {
                        break;
                    }
                }
                map(context.getCurrentKey(), context.getCurrentValue(), context);
            }
            cleanup(context);
        } finally {
            try {
                recordWriter.close();
                extTableThread.join();
            } catch (Exception e) {
                LOG.debug("Exception cleaning up mapper operation : " + e.getMessage());
            }
            counter.stopClock();
            LOG.info("Transferred " + counter.toString());
            FileUploader.uploadFilesToDFS(taskAttemptDir.getAbsolutePath(), localLogDir, logDir,
                    context.getJobID().toString(), conf);

            if (extTableThread.hasExceptions()) {
                extTableThread.printException();
                throw new IOException(extTableThread.getException());
            }
        }

    }
}