Example usage for java.lang Runnable run

List of usage examples for java.lang Runnable run

Introduction

In this page you can find the example usage for java.lang Runnable run.

Prototype

public abstract void run();

Source Link

Document

When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.

Usage

From source file:com.amalto.workbench.compare.Utilities.java

public static void firePropertyChange(final ListenerList listenerList, final PropertyChangeEvent event) {
    if (listenerList == null || listenerList.isEmpty())
        return;/*  w w  w.  j  a v  a 2  s . co  m*/
    // Legacy listeners may expect to get notified in the UI thread
    Runnable runnable = new Runnable() {

        public void run() {
            if (listenerList != null) {
                Object[] listeners = listenerList.getListeners();
                for (int i = 0; i < listeners.length; i++) {
                    final IPropertyChangeListener listener = (IPropertyChangeListener) listeners[i];
                    SafeRunner.run(new ISafeRunnable() {

                        public void run() throws Exception {
                            listener.propertyChange(event);
                        }

                        public void handleException(Throwable exception) {
                            // Logged by SafeRunner
                        }
                    });
                }
            }
        }
    };
    if (Display.getCurrent() == null) {
        Display.getDefault().syncExec(runnable);
    } else {
        runnable.run();
    }
}

From source file:org.zenoss.app.consumer.metric.impl.OpenTsdbMetricService.java

/**
 * Checks {@link #collides(long, String)} until it returns false, or we give up.
 * Periodic checks are spaced out using an exponential back off.
 * @param incomingSize the number of metrics being added
 * @param clientId an identifier for the source of the metrics
 * @return false if and only if {@link #collides(long, String)} returned false before we gave up.
 *//*from   w ww  .  j  a  v a 2s .c om*/
private boolean keepsColliding(final long incomingSize, final String clientId, Runnable onCollision) {
    ExponentialBackOff backOffTracker = null;
    long retryAt = 0L;
    long backOff;
    int collisions = 0;
    while (true) {
        if (collisions > 0 && onCollision != null)
            onCollision.run();
        if (System.currentTimeMillis() > retryAt) {
            if (collides(incomingSize, clientId)) {
                metricsQueue.incrementClientCollision();
                collisions++;
                if (backOffTracker == null) {
                    backOffTracker = buildExponentialBackOff();
                }
                try {
                    backOff = backOffTracker.nextBackOffMillis();
                    retryAt = System.currentTimeMillis() + backOff;
                } catch (IOException e) {
                    // should never happen
                    log.error("Caught IOException backing off tracker.", e);
                    throw new RuntimeException(e);
                }
                long elapsed = backOffTracker.getElapsedTimeMillis();
                if (ExponentialBackOff.STOP == backOff) {
                    log.warn("Too many collisions ({}). Gave up after {}ms.", collisions, elapsed);
                    return true;
                } else {
                    log.debug("Collision detected ({} in {}ms). Backing off for {} ms", collisions, elapsed,
                            backOff);
                }
            } else {
                return false;
            }
        }
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            /* no biggie */ }
    }
}

From source file:it.polimi.tower4clouds.common.net.DefaultRestClient.java

@Override
public String execute(RestMethod method, String url, String jsonEntity, int expectedCode, int timeout,
        boolean async) throws UnexpectedAnswerFromServerException, IOException {
    Runnable command = new RequestExecutor(method, url, jsonEntity, expectedCode, timeout);
    if (async) {//from  w w w. j  av a 2s .  c om
        executor.execute(command);
        return null;
    } else {
        synchronized (responseLock) {
            ioExc = null;
            unexpectedExc = null;
            response = null;
            command.run();
            if (unexpectedExc != null) {
                throw unexpectedExc;
            } else if (ioExc != null) {
                throw ioExc;
            } else {
                return response;
            }
        }
    }
}

From source file:com.amazonaws.services.simpleworkflow.flow.worker.SynchronousRetrier.java

public void retry(Runnable r) {
    int attempt = 0;
    long startTime = System.currentTimeMillis();
    BackoffThrottler throttler = new BackoffThrottler(retryParameters.getInitialInterval(),
            retryParameters.getMaximumRetryInterval(), retryParameters.getBackoffCoefficient());
    boolean success = false;
    do {//w ww .j a va 2 s  .  c o  m
        try {
            attempt++;
            throttler.throttle();
            r.run();
            success = true;
            throttler.success();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        } catch (RuntimeException e) {
            throttler.failure();
            for (Class<?> exceptionToNotRetry : exceptionsToNotRetry) {
                if (exceptionToNotRetry.isAssignableFrom(e.getClass())) {
                    throw e;
                }
            }
            long elapsed = System.currentTimeMillis() - startTime;
            if (attempt > retryParameters.getMaximumRetries()
                    || (elapsed >= retryParameters.getExpirationInterval()
                            && attempt > retryParameters.getMinimumRetries())) {
                throw e;
            }
            log.warn("Retrying after failure", e);
        }
    } while (!success);
}

From source file:hudson.model.ResourceController.java

/**
 * Performs the task that requires the given list of resources.
 *
 * <p>//from   ww  w .j  ava 2  s. c  om
 * The execution is blocked until the resource is available.
 *
 * @throws InterruptedException
 *      the thread can be interrupted while waiting for the available resources.
 */
public void execute(Runnable task, ResourceActivity activity) throws InterruptedException {
    ResourceList resources = activity.getResourceList();
    synchronized (this) {
        while (inUse.isCollidingWith(resources))
            wait();

        // we have a go
        inProgress.add(activity);
        inUse = ResourceList.union(inUse, resources);
    }

    try {
        task.run();
    } finally {
        synchronized (this) {
            inProgress.remove(activity);
            inUse = ResourceList.union(resourceView);
            notifyAll();
        }
    }
}

From source file:com.drunkendev.io.recurse.tests.RecursionTest.java

/**
 * Times a {@link Runnable} instance./*w ww  . j av a2 s .c o  m*/
 *
 * @param   r
 *          {@link Runnable} object to time.
 * @return  {@link Duration} object containing run-time length.
 */
public Duration time(Runnable r) {
    Instant start = Instant.now();
    r.run();
    Duration dur = Duration.between(start, Instant.now());
    System.out.format("Completed in: %s%n", dur.toString());
    return dur;
}

From source file:com.haulmont.cuba.desktop.sys.vcl.CollapsiblePanel.java

@Override
public void paint(Graphics g) {
    super.paint(g);

    SwingUtilities.invokeLater(new Runnable() {
        @Override//from   ww w  .j a v  a  2s  .  co m
        public void run() {
            for (Runnable action : postPaintActions) {
                action.run();
            }

            postPaintActions.clear();
        }
    });
}

From source file:ddf.catalog.registry.transformer.RegistryServiceConverter.java

private void safeMove(HierarchicalStreamReader reader, Integer amount, Runnable callback) {
    for (int i = 0; i < amount; i++) {
        reader.moveDown();//from   w w  w.  ja va  2s  .  com
    }
    try {
        callback.run();
    } finally {
        for (int i = 0; i < amount; i++) {
            reader.moveUp();
        }
    }
}

From source file:com.microsoft.tfs.client.clc.wit.commands.CommandGet.java

private void computeLinkDescriptions(final LinkCollection linkCollection) {
    final DescriptionUpdateErrorCallback errorCallback = new DescriptionUpdateErrorCallback() {
        @Override/*from  w w  w  .  j  a v a2 s .c o  m*/
        public void onDescriptionUpdateError(final Throwable error) {
            log.error(Messages.getString("CommandGet.ErrorUpdatingWorkItemLinkDescriptions"), error); //$NON-NLS-1$
        }
    };

    final LinkCollectionImpl linkCollectionImpl = (LinkCollectionImpl) linkCollection;
    final Runnable runnable = linkCollectionImpl.getDescriptionUpdateRunnable(errorCallback, null);

    /*
     * In a GUI application, the link description updater would probably be
     * run in a background thread Since we're CLI, we just run it
     * synchronously
     */
    runnable.run();
}

From source file:com.kenai.redminenb.query.RedmineQuery.java

protected void executeQuery(Runnable r) {
    fireStarted();/*  www .  j a  v a2s  .com*/
    try {
        r.run();
    } finally {
        fireFinished();
        fireQueryIssuesChanged();
        lastRefresh = System.currentTimeMillis();
    }
}