Example usage for java.lang Object wait

List of usage examples for java.lang Object wait

Introduction

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

Prototype

public final void wait() throws InterruptedException 

Source Link

Document

Causes the current thread to wait until it is awakened, typically by being notified or interrupted.

Usage

From source file:EmbeddedBroker.java

public static void main(String[] args) throws Exception {
    BrokerService broker = new BrokerService();
    broker.setUseJmx(true);/*w w  w  .  j a v  a 2s . co  m*/
    broker.addConnector("tcp://localhost:61616");
    broker.start();

    // now lets wait forever to avoid the JVM terminating immediately
    Object lock = new Object();
    synchronized (lock) {
        lock.wait();
    }
}

From source file:edu.stanford.junction.sample.sql.SQLActor.java

public static void main(String[] argv) {
    try {//from  ww w . j  a  v a2  s .  co  m
        System.out.println("Starting the database actor");
        JSONObject activity = new JSONObject();
        activity.put("sessionID", "sqlQuerySession");
        activity.put("ad", "edu.stanford.prpl.junction.demo.sql");

        XMPPSwitchboardConfig config = new XMPPSwitchboardConfig("prpl.stanford.edu");
        JunctionMaker jm = JunctionMaker.getInstance(config);
        Junction jx = jm.newJunction(new ActivityScript(activity), new SQLActor());

        /*
        try {
           Thread.sleep(3000);
           JSONObject msg = new JSONObject();
           msg.put("query","select count(*) from jz_nodes");
           jx.sendMessageToSession(msg);
        } catch (Exception e) {
           e.printStackTrace();
        }
        */

        Object dud = new Object();
        synchronized (dud) {
            dud.wait();
        }

    } catch (Exception e) {
        System.err.println("fail.");
        e.printStackTrace();
    }
}

From source file:com.sm.replica.grizzly.DefaultReplicaServer.java

public static void main(String[] args) {
    String[] opts = new String[] { "-store", "-path", "-port", "-mode", "index" };
    String[] defaults = new String[] { "replica", "./data", "7120", "0", "0" };
    String[] paras = getOpts(args, opts, defaults);
    String store = paras[0];//from w  w w .  j a va  2s.com
    int port = Integer.valueOf(paras[2]);
    String path = paras[1];
    int mode = Integer.valueOf(paras[3]);
    int index = Integer.valueOf(paras[4]);
    CacheStore cacheStore = new CacheStore(path, null, mode);
    LogChannel logChannel = new LogChannel(store, index, path);
    DefaultReplicaServer defaultReplicaServer = new DefaultReplicaServer(logChannel, index, store, path);
    HashMap<String, CacheStore> storesMap = new HashMap<String, CacheStore>();
    storesMap.put(store, cacheStore);
    UnisonFilter unisonServerFilter = new UnisonFilter(defaultReplicaServer);
    unisonServerFilter.setFreq(1);
    logger.info("start server at " + port);
    ReplicaServer server = new ReplicaServer(port, storesMap, unisonServerFilter);
    defaultReplicaServer.hookShutdown();
    logger.info("set main thread to wait()");
    try {
        //System.in.read();
        Object obj = new Object();
        synchronized (obj) {
            obj.wait();
        }
    } catch (Exception io) {
        logger.error(io.getMessage(), io);
    }
}

From source file:nz.co.jsrsolutions.ds3.DataScraper3.java

public static void main(String[] args) {

    logger.info("Starting application [ ds3 ] ...");

    ClassPathXmlApplicationContext context = null;

    try {/*from  ww  w .  ja v  a 2s.  c om*/

        CommandLineParser parser = new GnuParser();

        CommandLine commandLine = parser.parse(CommandLineOptions.Options, args);

        if (commandLine.getOptions().length > 0 && !commandLine.hasOption(CommandLineOptions.HELP)) {

            StringBuffer environment = new StringBuffer();
            environment.append(SPRING_CONFIG_PREFIX);
            environment.append(commandLine.getOptionValue(CommandLineOptions.ENVIRONMENT));
            environment.append(SPRING_CONFIG_SUFFIX);

            context = new ClassPathXmlApplicationContext(environment.toString());
            context.registerShutdownHook();

            if (commandLine.hasOption(CommandLineOptions.SCHEDULED)) {

                Scheduler scheduler = context.getBean(SCHEDULER_BEAN_ID, Scheduler.class);
                scheduler.start();

                Object lock = new Object();
                synchronized (lock) {
                    lock.wait();
                }

            } else {
                DataScraper3Controller controller = context.getBean(CONTROLLER_BEAN_ID,
                        DataScraper3Controller.class);
                controller.executeCommandLine(commandLine);
            }

        } else {

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("ds3", CommandLineOptions.Options);

        }

    } catch (DataScraper3Exception ds3e) {
        logger.error("Failed to execute command", ds3e);
    } catch (ParseException pe) {

        logger.error("Failed to parse command line", pe);

    } catch (Exception e) {

        logger.error("Failed to execute command", e);

    } finally {
        if (context != null) {
            context.close();
        }
    }

    logger.info("Exiting application [ ds3 ] ...");

}

From source file:nz.co.jsrsolutions.tideservice.scraper.TideScraper.java

public static void main(String[] args) {

    logger.info("Starting application [ tide scraper ] ...");

    GenericXmlApplicationContext context = null;

    try {/*from   w  ww .  j  a v a2s . c  o  m*/

        CommandLineParser parser = new GnuParser();

        CommandLine commandLine = parser.parse(CommandLineOptions.Options, args);

        if (commandLine.getOptions().length > 0 && !commandLine.hasOption(CommandLineOptions.HELP)) {

            context = new GenericXmlApplicationContext();

            //ConfigurableEnvironment env = ctx.getEnvironment();

            //env.setActiveProfiles("test1");

            context.load(SPRING_CONFIG);

            context.refresh();

            context.registerShutdownHook();

            if (commandLine.hasOption(CommandLineOptions.SCHEDULED)) {

                Scheduler scheduler = context.getBean(SCHEDULER_BEAN_ID, Scheduler.class);
                scheduler.start();

                Object lock = new Object();
                synchronized (lock) {
                    lock.wait();
                }

            } else {
                TideScraperController controller = context.getBean(CONTROLLER_BEAN_ID,
                        TideScraperController.class);
                controller.executeCommandLine(commandLine);
            }

        } else {

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("ts", CommandLineOptions.Options);

        }

    } catch (TideScraperException tse) {
        logger.error("Failed to execute command", tse);
    } catch (ParseException pe) {

        logger.error("Failed to parse command line", pe);

    } catch (Exception e) {

        logger.error("Failed to execute command", e);

    } finally {
        if (context != null) {
            context.close();
        }
    }

    logger.info("Exiting application [ tide scraper ] ...");

}

From source file:ThreadViewer.java

public static void main(String[] args) {
    JFrame f = new JFrame();
    ThreadViewer viewer = new ThreadViewer();

    f.setContentPane(viewer);//from www .  j a  v a  2 s .c  om
    f.setSize(500, 300);
    f.setVisible(true);

    f.setDefaultCloseOperation(1);

    // Keep the main thread from exiting by blocking
    // on wait() for a notification that never comes.
    Object lock = new Object();
    synchronized (lock) {
        try {
            lock.wait();
        } catch (InterruptedException x) {
        }
    }
}

From source file:com.lucidtechnics.blackboard.examples.cocothemonkey.CocoTheMonkey.java

public static void main(String[] _args) throws Exception {
    try {/*from  w  w  w.  j  a va 2 s.  c  o  m*/
        final Blackboard blackboard = new Blackboard();

        logger.info("Starting Coco The Monkey");
        System.out.println("Starting Coco The Monkey");

        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                synchronized (blackboard) {
                    try {
                        blackboard.wait();
                    } catch (InterruptedException e) {
                    }
                }

                for (int i = 0; i < 100; i++) {
                    Monkey monkey = new Monkey("Coco-1-" + i);
                    Mango mango = new Mango("Coco-2-" + i);
                    Eagle eagle = new Eagle("Coco-3-" + i);
                    Hunter hunter = new Hunter("Coco-5-" + i);

                    blackboard.placeOnBlackboard(eagle);
                    blackboard.placeOnBlackboard(mango);
                    blackboard.placeOnBlackboard(monkey);
                    blackboard.placeOnBlackboard(hunter);
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                synchronized (blackboard) {
                    try {
                        blackboard.wait();
                    } catch (InterruptedException e) {
                    }
                }

                for (int i = 0; i < 100; i++) {
                    Monkey monkey = new Monkey("Coco-4-" + i);
                    Mango mango = new Mango("Coco-1-" + i);
                    Eagle eagle = new Eagle("Coco-5-" + i);
                    Hunter hunter = new Hunter("Coco-3-" + i);

                    blackboard.placeOnBlackboard(eagle);
                    blackboard.placeOnBlackboard(mango);
                    blackboard.placeOnBlackboard(monkey);
                    blackboard.placeOnBlackboard(hunter);
                }
            }
        });

        Thread thread3 = new Thread(new Runnable() {
            public void run() {
                synchronized (blackboard) {
                    try {
                        blackboard.wait();
                    } catch (InterruptedException e) {
                    }
                }

                for (int i = 0; i < 100; i++) {
                    Monkey monkey = new Monkey("Coco-3-" + i);
                    Mango mango = new Mango("Coco-5-" + i);
                    Eagle eagle = new Eagle("Coco-4-" + i);
                    Hunter hunter = new Hunter("Coco-2-" + i);

                    blackboard.placeOnBlackboard(eagle);
                    blackboard.placeOnBlackboard(mango);
                    blackboard.placeOnBlackboard(monkey);
                    blackboard.placeOnBlackboard(hunter);
                }
            }
        });

        Thread thread4 = new Thread(new Runnable() {
            public void run() {
                synchronized (blackboard) {
                    try {
                        blackboard.wait();
                    } catch (InterruptedException e) {
                    }
                }

                for (int i = 0; i < 100; i++) {
                    Monkey monkey = new Monkey("Coco-2-" + i);
                    Mango mango = new Mango("Coco-3-" + i);
                    Eagle eagle = new Eagle("Coco-1-" + i);
                    Hunter hunter = new Hunter("Coco-4-" + i);

                    blackboard.placeOnBlackboard(eagle);
                    blackboard.placeOnBlackboard(mango);
                    blackboard.placeOnBlackboard(monkey);
                    blackboard.placeOnBlackboard(hunter);
                }
            }
        });

        Thread thread5 = new Thread(new Runnable() {
            public void run() {
                synchronized (blackboard) {
                    try {
                        blackboard.wait();
                    } catch (InterruptedException e) {
                    }
                }

                for (int i = 0; i < 100; i++) {
                    Monkey monkey = new Monkey("Coco-5-" + i);
                    Mango mango = new Mango("Coco-4-" + i);
                    Eagle eagle = new Eagle("Coco-2-" + i);
                    Hunter hunter = new Hunter("Coco-1-" + i);

                    blackboard.placeOnBlackboard(eagle);
                    blackboard.placeOnBlackboard(mango);
                    blackboard.placeOnBlackboard(monkey);
                    blackboard.placeOnBlackboard(hunter);
                }
            }
        });

        thread1.start();
        thread2.start();

        thread3.start();
        thread4.start();
        thread5.start();

        try {
            Thread.currentThread().sleep(1000);
        } catch (Throwable t) {
        }

        synchronized (blackboard) {
            blackboard.notifyAll();
        }

        Object object = new Object();

        synchronized (object) {
            try {
                object.wait();
            } catch (InterruptedException e) {
            }
        }
    } finally {
    }
}

From source file:org.apache.tuscany.sca.node.launcher.NodeLauncher.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new PosixParser();
    Options options = getCommandLineOptions();
    CommandLine cli = parser.parse(options, args);

    Object node = null;/*from  www . j a v  a2s. c o m*/
    ShutdownThread shutdown = null;
    try {
        while (true) {
            if (cli.hasOption("node")) {

                // Create a node from a configuration URI
                String configurationURI = cli.getOptionValue("node");
                logger.info("SCA Node configuration: " + configurationURI);
                // Create a node launcher
                NodeLauncher launcher = newInstance();
                node = launcher.createNodeFromURL(configurationURI);
            } else {

                // Create a node from a composite URI and a contribution location
                String compositeURI = cli.getOptionValue("composite");
                List<String> contribs = cli.getArgList();
                Contribution[] contributions = null;
                if (!contribs.isEmpty()) {
                    contributions = new Contribution[contribs.size()];
                    int index = 0;
                    for (String contrib : contribs) {
                        logger.info("SCA contribution: " + contrib);
                        URL url = null;
                        try {
                            url = new URL(contrib);
                        } catch (MalformedURLException e) {
                            url = new File(contrib).toURI().toURL();
                        }
                        contributions[index] = new Contribution("contribution-" + index, url.toString());
                        index++;
                    }
                } else {
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.setSyntaxPrefix("Usage: ");
                    formatter.printHelp("java " + NodeLauncher.class.getName() + " [-c <compositeURI>]"
                            + " [-s <service>]" + " [-t <ttl>]" + " contribution1 ... contributionN", options);
                    return;
                }
                // Create a node launcher
                logger.info("SCA composite: " + compositeURI);
                NodeLauncher launcher = newInstance();

                node = launcher.createNode(compositeURI, contributions);
            }

            logger.info("Apache Tuscany SCA Node is starting...");

            // Start the node
            try {
                node.getClass().getMethod("start").invoke(node);
            } catch (Exception e) {
                logger.log(Level.SEVERE, "SCA Node could not be started", e);
                throw e;
            }
            logger.info("SCA Node is now started.");

            String service = cli.getOptionValue("service");
            String regex = "(#|\\(|,|\\))";
            if (service != null) {
                // componentName/serviceName/bindingName#methodName(arg0, ..., agrN)
                String tokens[] = service.split(regex);
                String serviceName = tokens[0];
                String operationName = tokens[1];
                String params[] = new String[tokens.length - 2];
                System.arraycopy(tokens, 2, params, 0, params.length);
                logger.info("Invoking service: " + service);
                Method method = node.getClass().getMethod("getService", Class.class, String.class);
                Object proxy = method.invoke(node, null, serviceName);

                Object result = invoke(proxy, operationName, params);
                if (result != null) {
                    logger.info("Result is: " + result);
                }
                break;
            }

            // Install a shutdown hook
            shutdown = new ShutdownThread(node);
            Runtime.getRuntime().addShutdownHook(shutdown);

            long ttl = Long.parseLong(cli.getOptionValue("ttl", "-1"));
            if (ttl >= 0) {
                logger.info("Waiting for " + ttl + " milliseconds ...");
                Thread.sleep(ttl);
                // Stop the node
                if (node != null) {
                    Object n = node;
                    node = null;
                    stopNode(n);
                }
                break; // Exit
            }

            logger.info("Press 'q' to quit, 'r' to restart.");
            int k = 0;
            try {
                while ((k != 'q') && (k != 'r')) {
                    k = System.in.read();
                }
            } catch (IOException e) {

                // Wait forever
                Object lock = new Object();
                synchronized (lock) {
                    lock.wait();
                }
            }

            // Stop the node
            if (node != null) {
                Object n = node;
                node = null;
                stopNode(n);
            }

            // Quit
            if (k == 'q') {
                break;
            }
        }
    } catch (Exception e) {
        // Stop the node
        if (node != null) {
            try {
                Object n = node;
                node = null;
                stopNode(n);
            } catch (Exception e2) {
            }
        }
        throw e;

    } finally {

        // Remove the shutdown hook
        if (shutdown != null) {
            Runtime.getRuntime().removeShutdownHook(shutdown);
        }
    }
}

From source file:org.apache.tuscany.sca.node.equinox.launcher.NodeLauncher.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new PosixParser();
    Options options = getCommandLineOptions();
    CommandLine cli = parser.parse(options, args);

    Object node = null;//from  w  w w. j  a v a2 s .c  o m
    ShutdownThread shutdown = null;
    EquinoxHost equinox = null;
    try {

        if (cli.hasOption("config")) {
            System.setProperty("osgi.configuration.area", cli.getOptionValue("config"));
        }

        while (true) {
            if (cli.hasOption("node")) {
                // Create a node from a configuration URI
                String configurationURI = cli.getOptionValue("node");
                logger.info("SCA Node configuration: " + configurationURI);

                // Create a node launcher
                NodeLauncher launcher = newInstance();
                equinox = launcher.equinoxHost;

                node = launcher.createNode(configurationURI);
            } else if (cli.hasOption("bundles")) {
                /**
                 * osgi.bundles
                 * The comma-separated list of bundles which are automatically installed and optionally started once the system is up
                 * and running. Each entry is of the form:
                 * <URL | simple bundle location>[@ [<start-level>] [":start"]]
                 * If the start-level (>0 integer) is omitted then the framework will use the default start level for the bundle.
                 * If the "start" tag is added then the bundle will be marked as started after being installed. Simple bundle locations are
                 * interepreted as relative to the framework's parent directory. The start-level indicates the OSGi start level at which the
                 * bundle should run. If this value is not set, the system computes an appropriate default.
                 */
                String bundles = cli.getOptionValue("bundles");
                if (bundles != null) {
                    System.setProperty("osgi.bundles", cli.getOptionValue("bundles"));
                }

                // Create a node launcher
                NodeLauncher launcher = newInstance();
                equinox = launcher.equinoxHost;

                /*
                List<String> bundleFiles = cli.getArgList();
                for (String bf : bundleFiles) {
                File f = new File(bf);
                equinox.installBundle(f.toURI().toURL(), null);
                }
                for (Bundle b : launcher.bundleContext.getBundles()) {
                try {
                    if (b.getHeaders().get(Constants.FRAGMENT_HOST) == null) {
                        // Start the non-fragment bundle
                        b.start();
                    }
                } catch (Exception e) {
                    logger.severe(NodeLauncherUtil.string(b, false) + " " + e.getMessage());
                    // logger.log(Level.SEVERE, e.getMessage(), e);
                }
                }
                */

            } else {
                // Create a node from a composite URI and a contribution location
                String compositeURI = cli.getOptionValue("composite");
                List<String> contribs = cli.getArgList();
                Contribution[] contributions = null;
                if (!contribs.isEmpty()) {
                    contributions = new Contribution[contribs.size()];
                    int index = 0;
                    for (String contrib : contribs) {
                        logger.info("SCA contribution: " + contrib);
                        URL url = null;
                        try {
                            url = new URL(contrib);
                        } catch (MalformedURLException e) {
                            url = new File(contrib).toURI().toURL();
                        }
                        contributions[index] = new Contribution("contribution-" + index, url.toString());
                        index++;
                    }
                } else {
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.setSyntaxPrefix("Usage: ");
                    formatter.printHelp("java " + NodeLauncher.class.getName()
                            + " [-config <equinoxConfiguration>]" + " [-c <compositeURI>]" + " [-b <bundles>]"
                            + " [-t <ttl>]" + " contribution1 ... contributionN", options);
                    return;
                }
                // Create a node launcher
                logger.info("SCA composite: " + compositeURI);
                NodeLauncher launcher = newInstance();
                equinox = launcher.equinoxHost;
                node = launcher.createNode(compositeURI, contributions);
            }

            if (node != null) {
                logger.info("Apache Tuscany SCA Node is starting...");

                // Start the node
                try {
                    node.getClass().getMethod("start").invoke(node);
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "SCA Node could not be started", e);
                    throw e;
                }
                logger.info("SCA Node is now started.");
            }
            // Install a shutdown hook
            shutdown = new ShutdownThread(node, equinox);
            Runtime.getRuntime().addShutdownHook(shutdown);

            long ttl = Long.parseLong(cli.getOptionValue("ttl", "-1"));
            if (ttl >= 0) {
                logger.info("Waiting for " + ttl + " milliseconds ...");
                Thread.sleep(ttl);
                break; // Exit
            }

            // Wait until the "Enter" is pressed
            logger.info("Press 'q' to quit, 'r' to restart.");
            int k = 0;
            try {
                while ((k != 'q') && (k != 'r')) {
                    k = System.in.read();
                }
            } catch (IOException e) {

                // Wait forever
                Object lock = new Object();
                synchronized (lock) {
                    lock.wait();
                }
            }

            // Stop the node
            if (node != null) {
                Object n = node;
                node = null;
                stopNode(n);
            }

            // Quit
            if (k == 'q') {
                break;
            }

        }
    } finally {

        // Remove the shutdown hook
        if (shutdown != null) {
            Runtime.getRuntime().removeShutdownHook(shutdown);
        }

        // Stop the node
        if (node != null) {
            destroyNode(node);
        }
        if (equinox != null) {
            equinox.stop();
        }
    }
}

From source file:org.apache.flink.runtime.jobmanager.JobManager.java

/**
 * Entry point for the program//from w  ww  .j a  va  2  s .c o  m
 * 
 * @param args
 *        arguments from the command line
 */

public static void main(String[] args) {

    JobManager jobManager;
    try {
        jobManager = initialize(args);
        // Start info server for jobmanager
        jobManager.startInfoServer();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        System.exit(FAILURE_RETURN_CODE);
    }

    // Clean up is triggered through a shutdown hook
    // freeze this thread to keep the JVM alive (the job manager threads are daemon threads)
    Object w = new Object();
    synchronized (w) {
        try {
            w.wait();
        } catch (InterruptedException e) {
        }
    }
}