Example usage for java.lang Thread holdsLock

List of usage examples for java.lang Thread holdsLock

Introduction

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

Prototype

public static native boolean holdsLock(Object obj);

Source Link

Document

Returns true if and only if the current thread holds the monitor lock on the specified object.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Object o = new Object();

    System.out.println(Thread.holdsLock(o));
    synchronized (o) {
        System.out.println(Thread.holdsLock(o));
    }//from   w  w  w. j a va2 s. co m
}

From source file:Main.java

/**
 * Wait on the given object for the specified number of milliseconds.
 * This method will return the actual amount of time that was waited.
 * The current thread must hold the lock on the given object. 
 *///from ww w.j a  v  a2 s . co m
public static long wait(Object o, long timeout) {
    long start = System.currentTimeMillis();
    if (Thread.holdsLock(o)) {
        try {
            o.wait(timeout);
        } catch (InterruptedException e) {
        }
    }
    return System.currentTimeMillis() - start;
}

From source file:Main.java

/**
 * Wait on the given object indefinitely. This method will return false
 * if an error occured while waiting. The current thread must hold the 
 * lock on the given object. /*from  w  w  w.j  av a 2  s.  c  o  m*/
 */
public static boolean wait(Object o) {
    if (Thread.holdsLock(o)) {
        try {
            o.wait();
            return true;
        } catch (InterruptedException e) {
            return false;
        }
    }
    return false;
}

From source file:ThreadDemo.java

public void run() {

    System.out.println("Holds Lock = " + Thread.holdsLock(this));

    synchronized (this) {
        System.out.println("Holds Lock = " + Thread.holdsLock(this));
    }//  w  w w .j a va2  s. c  o  m
}

From source file:Main.java

private static boolean isKnownRoot(X509Certificate root) throws NoSuchAlgorithmException, KeyStoreException {
    assert Thread.holdsLock(sLock);

    // Could not find the system key store. Conservatively report false.
    if (sSystemKeyStore == null)
        return false;

    // Check the in-memory cache first; avoid decoding the anchor from disk
    // if it has been seen before.
    Pair<X500Principal, PublicKey> key = new Pair<X500Principal, PublicKey>(root.getSubjectX500Principal(),
            root.getPublicKey());//from w  ww.j  a  v a2  s.c  om

    if (sSystemTrustAnchorCache.contains(key))
        return true;

    // Note: It is not sufficient to call sSystemKeyStore.getCertificiateAlias. If the server
    // supplies a copy of a trust anchor, X509TrustManagerExtensions returns the server's
    // version rather than the system one. getCertificiateAlias will then fail to find an anchor
    // name. This is fixed upstream in https://android-review.googlesource.com/#/c/91605/
    //
    // TODO(davidben): When the change trickles into an Android release, query sSystemKeyStore
    // directly.

    // System trust anchors are stored under a hash of the principal. In case of collisions,
    // a number is appended.
    String hash = hashPrincipal(root.getSubjectX500Principal());
    for (int i = 0; true; i++) {
        String alias = hash + '.' + i;
        if (!new File(sSystemCertificateDirectory, alias).exists())
            break;

        Certificate anchor = sSystemKeyStore.getCertificate("system:" + alias);
        // It is possible for this to return null if the user deleted a trust anchor. In
        // that case, the certificate remains in the system directory but is also added to
        // another file. Continue iterating as there may be further collisions after the
        // deleted anchor.
        if (anchor == null)
            continue;

        if (!(anchor instanceof X509Certificate)) {
            // This should never happen.
            String className = anchor.getClass().getName();
            Log.e(TAG, "Anchor " + alias + " not an X509Certificate: " + className);
            continue;
        }

        // If the subject and public key match, this is a system root.
        X509Certificate anchorX509 = (X509Certificate) anchor;
        if (root.getSubjectX500Principal().equals(anchorX509.getSubjectX500Principal())
                && root.getPublicKey().equals(anchorX509.getPublicKey())) {
            sSystemTrustAnchorCache.add(key);
            return true;
        }
    }

    return false;
}

From source file:com.chiorichan.event.EventBus.java

/**
 * Calls an event with the given details.<br>
 * This method only synchronizes when the event is not asynchronous.
 * /*w  w  w .  j  ava 2 s.c o m*/
 * @param event
 *            Event details
 */
public void callEvent(Event event) {
    try {
        if (event.isAsynchronous()) {
            if (Thread.holdsLock(this)) {
                throw new IllegalStateException(event.getEventName()
                        + " cannot be triggered asynchronously from inside synchronized code.");
            }
            if (Loader.getConsole().isPrimaryThread()) {
                throw new IllegalStateException(event.getEventName()
                        + " cannot be triggered asynchronously from primary server thread.");
            }
            fireEvent(event);
        } else {
            synchronized (this) {
                fireEvent(event);
            }
        }
    } catch (EventException ex) {

    }
}

From source file:com.chiorichan.event.EventBus.java

/**
 * Calls an event with the given details.<br>
 * This method only synchronizes when the event is not asynchronous.
 * //  w w w. j  av a 2s.  c  o  m
 * @param event
 *            Event details
 * @throws EventException
 */
public void callEventWithException(Event event) throws EventException {
    if (event.isAsynchronous()) {
        if (Thread.holdsLock(this)) {
            throw new IllegalStateException(event.getEventName()
                    + " cannot be triggered asynchronously from inside synchronized code.");
        }
        if (Loader.getConsole().isPrimaryThread()) {
            throw new IllegalStateException(
                    event.getEventName() + " cannot be triggered asynchronously from primary server thread.");
        }
        fireEvent(event);
    } else {
        synchronized (this) {
            fireEvent(event);
        }
    }
}

From source file:eu.udig.catalog.jgrass.utils.JGrassCatalogUtilities.java

/**
 * Reload the service, to which the location refers to. This is ment to be used when new maps
 * are added inside a mapset and the catalog doesn't care to see them. So the tree has to be
 * reloaded./*  w w w .j a  v  a2s  .  com*/
 * 
 * @param locationPath the path to the affected location
 * @param monitor the progress monitor
 */
public static void refreshJGrassService(String locationPath, final IProgressMonitor monitor) {

    System.out.println("Lock on locationPath = " + Thread.holdsLock(locationPath));
    synchronized (locationPath) {

        /*
         * if the catalog is active, refresh the location in the catalog window
         */
        ID id = null;
        if (JGrassPlugin.getDefault() != null) {
            File locationFile = new File(locationPath);
            try {
                id = new ID(locationFile.toURI().toURL());
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return;
            }
        } else {
            return;
        }
        /*
         * test code to make the catalog understand that the map should be added
         */
        final ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();
        final JGrassService originalJGrassService = catalog.getById(JGrassService.class, id, monitor);

        /*
         * create the same service
         */
        if (originalJGrassService == null)
            return;
        final URL ID = originalJGrassService.getIdentifier();
        Map<String, Serializable> connectionParams = originalJGrassService.getConnectionParams();
        IServiceFactory locator = CatalogPlugin.getDefault().getServiceFactory();
        final List<IService> rereadService = locator.acquire(ID, connectionParams);

        /*
         * replace the service
         */
        if (rereadService.size() > 0) {
            Runnable refreshCatalogRunner = new Runnable() {
                public void run() {
                    final IService newJGrassService = rereadService.get(0);
                    catalog.remove(originalJGrassService);
                    catalog.add(newJGrassService);
                }
            };

            new Thread(refreshCatalogRunner).start();
        }
    }
}

From source file:com.vmware.aurora.vc.vcservice.VcService.java

private void setService(ServiceContents service, VcConnectionStatusChangeEvent eventType) {
    AuAssert.check(Thread.holdsLock(this));
    /*/*from www. j a  v  a2  s.c  o  m*/
     * Always log an event for an initial attempt: both VcContext is
     * initialized for the first time and this session gets its first life.
     * Otherwise, log an an event only if a service state change has been
     * detected to avoid event storms when VC is persistently down.
     */
    if (eventType != null && ((VcContext.getGenCount() == 1 && curGenCount == 1) || this.service != service)) {
        VcContext.triggerEvent(eventType, serviceName);
    }
    this.service = service;
}

From source file:it.unibo.alchemist.boundary.monitors.Generic2DDisplay.java

private void update(final Environment<T> env, final Time time) {
    if (Thread.holdsLock(env)) {
        if (envHasMobileObstacles(env)) {
            loadObstacles(env);//from ww  w.  j av  a  2 s  .c o  m
        }
        lasttime = time.toDouble();
        currentEnv = env;
        accessData();
        positions.clear();
        neighbors.clear();
        env.getNodes().parallelStream().forEach(node -> {
            positions.put(node, env.getPosition(node));
            try {
                neighbors.put(node, env.getNeighborhood(node).clone());
            } catch (Exception e) {
                L.error("Unable to clone neighborhood for " + node, e);
            }
        });
        releaseData();
        repaint();
    } else {
        throw new IllegalStateException("Only the simulation thread can dictate GUI updates");
    }
}