Example usage for java.lang Object notify

List of usage examples for java.lang Object notify

Introduction

In this page you can find the example usage for java.lang Object notify.

Prototype

@HotSpotIntrinsicCandidate
public final native void notify();

Source Link

Document

Wakes up a single thread that is waiting on this object's monitor.

Usage

From source file:com.gigaspaces.internal.utils.ClassLoaderCleaner.java

private static void clearReferencesStopTimerThread(Thread thread) {

    // Need to get references to:
    // - newTasksMayBeScheduled field
    // - queue field
    // - queue.clear()

    try {//from   w  ww.  ja va  2s  .c o  m
        Field newTasksMayBeScheduledField = thread.getClass().getDeclaredField("newTasksMayBeScheduled");
        newTasksMayBeScheduledField.setAccessible(true);
        Field queueField = thread.getClass().getDeclaredField("queue");
        queueField.setAccessible(true);

        Object queue = queueField.get(thread);

        Method clearMethod = queue.getClass().getDeclaredMethod("clear");
        clearMethod.setAccessible(true);

        synchronized (queue) {
            newTasksMayBeScheduledField.setBoolean(thread, false);
            clearMethod.invoke(queue);
            queue.notify(); // In case queue was already empty.
        }

        if (logger.isLoggable(Level.FINE))
            logger.fine("A web application appears to have started a TimerThread named [" + thread.getName()
                    + "] via the java.util.Timer API but has failed to stop it. To prevent a memory leak, the timer (and hence the associated thread) has been forcibly cancelled.");

    } catch (Exception e) {
        logger.log(Level.WARNING, "Failed to terminate TimerThread named [" + thread.getName() + "]", e);
    }
}

From source file:com.duker.mygift.struts.interceptor.ScopeInterceptor.java

static final void lock(Object o, ActionInvocation invocation) throws Exception {
    synchronized (o) {
        int count = 3;
        Object previous = null;/*  w w w  .  j  av  a2 s. com*/
        while ((previous = locks.get(o)) != null) {
            if (previous == invocation) {
                return;
            }
            if (count-- <= 0) {
                locks.remove(o);
                o.notify();

                throw new StrutsException("Deadlock in session lock");
            }
            o.wait(10000);
        }
        locks.put(o, invocation);
    }
}

From source file:org.sufficientlysecure.keychain.service.PassphraseCacheService.java

/**
 * Gets a cached passphrase from memory by sending an intent to the service. This method is
 * designed to wait until the service returns the passphrase.
 *
 * @param context//from   w  w w.  j  a  va  2 s. com
 * @param keyId
 * @return passphrase or null (if no passphrase is cached for this keyId)
 */
public static String getCachedPassphrase(Context context, long keyId) {
    Log.d(TAG, "getCachedPassphrase() get masterKeyId for " + keyId);

    Intent intent = new Intent(context, PassphraseCacheService.class);
    intent.setAction(ACTION_PASSPHRASE_CACHE_GET);

    final Object mutex = new Object();
    final Bundle returnBundle = new Bundle();

    HandlerThread handlerThread = new HandlerThread("getPassphraseThread");
    handlerThread.start();
    Handler returnHandler = new Handler(handlerThread.getLooper()) {
        @Override
        public void handleMessage(Message message) {
            if (message.obj != null) {
                String passphrase = ((Bundle) message.obj).getString(EXTRA_PASSPHRASE);
                returnBundle.putString(EXTRA_PASSPHRASE, passphrase);
            }
            synchronized (mutex) {
                mutex.notify();
            }
            // quit handlerThread
            getLooper().quit();
        }
    };

    // Create a new Messenger for the communication back
    Messenger messenger = new Messenger(returnHandler);
    intent.putExtra(EXTRA_KEY_ID, keyId);
    intent.putExtra(EXTRA_MESSENGER, messenger);
    // send intent to this service
    context.startService(intent);

    // Wait on mutex until passphrase is returned to handlerThread
    synchronized (mutex) {
        try {
            mutex.wait(3000);
        } catch (InterruptedException e) {
        }
    }

    if (returnBundle.containsKey(EXTRA_PASSPHRASE)) {
        return returnBundle.getString(EXTRA_PASSPHRASE);
    } else {
        return null;
    }
}

From source file:uk.org.sappho.applications.transcript.service.report.restful.client.RestfulClientThread.java

public void run() {

    Object threadLock = restfulClientState.getThreadLock();
    synchronized (threadLock) {
        threadLock.notify();
        restfulClientState.setData(null);
        restfulClientState.setThrowable(null);
        HttpURLConnection httpURLConnection = null;
        InputStream inputStream = null;
        try {// ww  w. j ava  2s.c om
            httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
            httpURLConnection.setConnectTimeout(connectTimeout);
            httpURLConnection.setReadTimeout(readTimeout);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setRequestProperty("User-Agent", "TranscriptRESTfulClient/1.0");
            httpURLConnection.connect();
            inputStream = httpURLConnection.getInputStream();
            restfulClientState.setData(IOUtils.toByteArray(inputStream));
            inputStream.close();
            inputStream = null;
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode != expectedResponseCode) {
                throw new TranscriptException("Expected " + key + " response " + expectedResponseCode
                        + " but got " + responseCode + " instead");
            }
        } catch (Throwable throwable) {
            restfulClientState.setThrowable(throwable);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Throwable throwable) {
                }
            }
            if (httpURLConnection != null) {
                try {
                    httpURLConnection.disconnect();
                } catch (Throwable throwable) {
                }
            }
        }
    }
}

From source file:Wake.java

public void wakeOne() {
    Object theLock = null;
    synchronized (stopped) {
        if (stopped.size() != 0) {
            theLock = stopped.firstElement();
            stopped.removeElementAt(0);//from w w  w. jav  a 2  s.  c om
        }
    }
    if (theLock != null) {
        synchronized (theLock) {
            theLock.notify();
        }
    }
}

From source file:net.sf.cindy.impl.AbstractSimulatedSession.java

public void close(boolean block) {
    if (!isAvailable())
        return;/*  ww w . j a  v  a  2s . com*/
    synchronized (this) {
        closing = true;
        synchronized (writeLocks) {
            for (Iterator iter = writeLocks.iterator(); iter.hasNext();) {
                Object writeLock = (Object) iter.next();
                iter.remove();
                synchronized (writeLock) {
                    writeLock.notify(); //Notify
                }
            }
        }
        idleTime = 0;
        doClose();
        if (Thread.currentThread() != thread && thread != null) {
            while (thread.isAlive()) {
                try {
                    thread.join();
                } catch (InterruptedException e) {
                }
            }
        }
        thread = null;
        closing = false;
        dispatchSessionClosed();
    }
}

From source file:it.osm.gtfs.GTFSOSMImport.java

@Command(description = "Analyze the diff between osm relations and gtfs trips")
public void reldiffx() throws IOException, ParserConfigurationException, SAXException {
    final Object lock = new Object();
    final GTFSRouteDiffGui app = new GTFSRouteDiffGui();

    app.setVisible(true);/*from ww  w .ja va 2 s.co m*/
    app.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent arg0) {
            synchronized (lock) {
                app.setVisible(false);
                lock.notify();
            }
        }

    });

    synchronized (lock) {
        while (app.isVisible())
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
    app.dispose();
    System.out.println("Done");
}

From source file:org.hyperledger.fabric.sdk.Peer.java

private boolean waitForInvokeComplete(final String txid) {
    int waitTime = this.chain.getInvokeWaitTime();
    logger.debug(String.format("waiting %d seconds before emitting invoke complete event", waitTime));

    final boolean[] invokeCompleted = { false };
    final Object lock = new Object();
    this.chain.getEventHub().registerTxEvent(txid, new TransactionListener() {
        @Override/*from w ww  . j ava 2 s .com*/
        public void process(Fabric.Transaction transaction) {
            chain.getEventHub().unregisterTxEvent(txid);
            invokeCompleted[0] = true;
            synchronized (lock) {
                lock.notify();
            }
        }
    });
    try {
        synchronized (lock) {
            lock.wait(waitTime * 1000);
        }
    } catch (InterruptedException e) {
        // ignore
    }
    return invokeCompleted[0];
}

From source file:org.hyperledger.fabric.sdk.Peer.java

private boolean waitForDeployComplete(final String txid) {
    int waitTime = this.chain.getDeployWaitTime();
    logger.debug(String.format("waiting %d seconds before emitting deploy complete event", waitTime));

    final boolean[] deployCompleted = { false };
    final Object lock = new Object();
    this.chain.getEventHub().registerTxEvent(txid, new TransactionListener() {
        @Override/*from  w  ww.j a va 2s.c o  m*/
        public void process(Fabric.Transaction transaction) {
            chain.getEventHub().unregisterTxEvent(txid);
            deployCompleted[0] = true;
            synchronized (lock) {
                lock.notify();
            }
        }
    });

    try {
        synchronized (lock) {
            lock.wait(waitTime * 1000);
        }
    } catch (InterruptedException e) {
        // ignore
    }
    return deployCompleted[0];
}

From source file:com.dumontierlab.pdb2rdf.Pdb2Rdf.java

private static ExecutorService getThreadPool(CommandLine cmd) {
    // twice the number of PU
    final Object monitor = new Object();
    int numberOfThreads = getNumberOfThreads(cmd);
    LOG.info("Using " + numberOfThreads + " threads.");
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(numberOfThreads, numberOfThreads, 10,
            TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(1), new RejectedExecutionHandler() {
                @Override//from   ww w  .j a  va 2 s  .c om
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    synchronized (monitor) {
                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                    executor.execute(r);
                }
            }) {
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            synchronized (monitor) {
                monitor.notify();
            }
            super.afterExecute(r, t);
        }
    };

    return threadPool;
}