Example usage for java.lang Thread currentThread

List of usage examples for java.lang Thread currentThread

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static native Thread currentThread();

Source Link

Document

Returns a reference to the currently executing thread object.

Usage

From source file:com.mohankri.createsetup.CreateSetup.java

public static void main(String[] args) throws InterruptedException {
    ZkServer server = null;/*from ww  w.  j av  a 2s  . c om*/
    System.out.println("Integration Test");
    ZkClient zkclient = null;
    try {
        String baseDir = "/tmp/IntegrationTest/";
        int zkPort = 2199;

        final String zkAddress = "localhost:" + zkPort;
        final String clusterName = "file-store-test1";
        /*
              ClusterSetup setup = new ClusterSetup(zkAddress);
              setup.deleteCluster(clusterName);
              setup.addCluster(clusterName, true);
              setup.addInstanceToCluster(clusterName, "localhost_12001");
              setup.addInstanceToCluster(clusterName, "localhost_12002");
              setup.addInstanceToCluster(clusterName, "localhost_12003");
              setup.addResourceToCluster(clusterName, "repository", 1, "MasterSlave");
              setup.rebalanceResource(clusterName, "repository", 2);  */

        zkclient = new ZkClient(zkAddress, ZkClient.DEFAULT_SESSION_TIMEOUT,
                ZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());

        ZKHelixAdmin admin = new ZKHelixAdmin(zkclient);
        admin.addCluster(clusterName, true);
        /*
              admin.addStateModelDef(clusterName, DEFAULT_STATE_MODEL,
                  new StateModelDefinition(StateModelConfigGenerator.generateConfigForMasterSlave())); */

        StateModelDefinition myStateModel = defineStateModel();

        System.out.println("Configuring StateModel: " + "MyStateModel  with 1 Master and 1 Slave");
        admin.addStateModelDef(clusterName, STATE_MODEL_NAME.stringify(), myStateModel);

        for (int i = 1; i < 4; i++) {
            String port = "" + (12000 + i);
            String serverId = "localhost_" + port;
            InstanceConfig config = new InstanceConfig(serverId);
            config.setHostName("localhost");
            config.setPort(port);
            config.setInstanceEnabled(true);
            admin.addInstance(clusterName, config);
        }
        //admin.addResource(clusterName, "repository", 1, DEFAULT_STATE_MODEL,
        //RebalanceMode.SEMI_AUTO.toString());

        admin.addResource(clusterName, "repository", 1, STATE_MODEL_NAME.stringify(), "FULL_AUTO");

        admin.rebalance(clusterName, "repository", 3);
        // Set the configuration
        /*
              final String instanceName1 = "localhost_12001";
              addConfiguration(setup, baseDir, clusterName, instanceName1);
              final String instanceName2 = "localhost_12002";
              addConfiguration(setup, baseDir, clusterName, instanceName2);
              final String instanceName3 = "localhost_12003";
              addConfiguration(setup, baseDir, clusterName, instanceName3); */

        //printStatus(manager);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (server != null) {
            // server.shutdown();
        }
    }
    Thread.currentThread().join();
    //Thread.sleep(600);
}

From source file:je3.rmi.MudClient.java

/**
 * The main program.  It expects two or three arguments:
 *   0) the name of the host on which the mud server is running
 *   1) the name of the MUD on that host
 *   2) the name of a place within that MUD to start at (optional).
 *
 * It uses the Naming.lookup() method to obtain a RemoteMudServer object
 * for the named MUD on the specified host.  Then it uses the getEntrance()
 * or getNamedPlace() method of RemoteMudServer to obtain the starting
 * RemoteMudPlace object.  It prompts the user for a their name and 
 * description, and creates a MudPerson object.  Finally, it passes
 * the person and the place to runMud() to begin interaction with the MUD.
 **///  w  ww .  j a v a  2  s.  co  m
public static void main(String[] args) {
    try {
        String hostname = args[0]; // Each MUD is uniquely identified by a 
        String mudname = args[1];  //   host and a MUD name.
        String placename = null;   // Each place in a MUD has a unique name
        if (args.length > 2) placename = args[2];
       
        // Look up the RemoteMudServer object for the named MUD using
        // the default registry on the specified host.  Note the use of
        // the Mud.mudPrefix constant to help prevent naming conflicts
        // in the registry.
        RemoteMudServer server = 
            (RemoteMudServer)Naming.lookup("rmi://" + hostname + "/" +
                  Mud.mudPrefix + mudname);

        // If the user did not specify a place in the mud, use
        // getEntrance() to get the initial place.  Otherwise, call
        // getNamedPlace() to find the initial place.
        RemoteMudPlace location = null;
        if (placename == null) location = server.getEntrance();
        else location = (RemoteMudPlace) server.getNamedPlace(placename);
       
        // Greet the user and ask for their name and description.
        // This relies on getLine() and getMultiLine() defined below.
        System.out.println("Welcome to " + mudname);
        String name = getLine("Enter your name: ");
        String description = getMultiLine("Please describe what " +
             "people see when they look at you:");

        // Define an output stream that the MudPerson object will use to
        // display messages sent to it to the user.  We'll use the console.
        PrintWriter myout = new PrintWriter(System.out);
       
        // Create a MudPerson object to represent the user in the MUD.
        // Use the specified name and description, and the output stream.
        MudPerson me = new MudPerson(name, description, myout);
       
        // Lower this thread's priority one notch so that broadcast
        // messages can appear even when we're blocking for I/O.  This is
        // necessary on the Linux platform, but may not be necessary on all
        // platforms.
        int pri = Thread.currentThread().getPriority();
        Thread.currentThread().setPriority(pri-1);
       
        // Finally, put the MudPerson into the RemoteMudPlace, and start
        // prompting the user for commands.
        runMud(location, me);
    }
    // If anything goes wrong, print a message and exit.
    catch (Exception e) {
        System.out.println(e);
        System.out.println("Usage: java MudClient <host> <mud> [<place>]");
        System.exit(1);
    }
}

From source file:MailHandlerDemo.java

/**
 * Runs the demo.//from w  w  w .j  a v a 2 s .c  o m
 *
 * @param args the command line arguments
 * @throws IOException if there is a problem.
 */
public static void main(String[] args) throws IOException {
    List<String> l = Arrays.asList(args);
    if (l.contains("/?") || l.contains("-?") || l.contains("-help")) {
        LOGGER.info("Usage: java MailHandlerDemo " + "[[-all] | [-body] | [-custom] | [-debug] | [-low] "
                + "| [-simple] | [-pushlevel] | [-pushfilter] " + "| [-pushnormal] | [-pushonly]] " + "\n\n"
                + "-all\t\t: Execute all demos.\n" + "-body\t\t: An email with all records and only a body.\n"
                + "-custom\t\t: An email with attachments and dynamic names.\n"
                + "-debug\t\t: Output basic debug information about the JVM " + "and log configuration.\n"
                + "-low\t\t: Generates multiple emails due to low capacity." + "\n"
                + "-simple\t\t: An email with all records with body and " + "an attachment.\n"
                + "-pushlevel\t: Generates high priority emails when the"
                + " push level is triggered and normal priority when " + "flushed.\n"
                + "-pushFilter\t: Generates high priority emails when the "
                + "push level and the push filter is triggered and normal " + "priority emails when flushed.\n"
                + "-pushnormal\t: Generates multiple emails when the "
                + "MemoryHandler push level is triggered.  All generated "
                + "email are sent as normal priority.\n" + "-pushonly\t: Generates multiple emails when the "
                + "MemoryHandler push level is triggered.  Generates high "
                + "priority emails when the push level is triggered and " + "normal priority when flushed.\n");
    } else {
        final boolean debug = init(l); //may create log messages.
        try {
            LOGGER.log(Level.FINEST, "This is the finest part of the demo.",
                    new MessagingException("Fake JavaMail issue."));
            LOGGER.log(Level.FINER, "This is the finer part of the demo.",
                    new NullPointerException("Fake bug."));
            LOGGER.log(Level.FINE, "This is the fine part of the demo.");
            LOGGER.log(Level.CONFIG, "Logging config file is {0}.", getConfigLocation());
            LOGGER.log(Level.INFO, "Your temp directory is {0}, " + "please wait...", getTempDir());

            try { //Waste some time for the custom formatter.
                Thread.sleep(3L * 1000L);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

            LOGGER.log(Level.WARNING, "This is a warning.",
                    new FileNotFoundException("Fake file chooser issue."));
            LOGGER.log(Level.SEVERE, "The end of the demo.", new IOException("Fake access denied issue."));
        } finally {
            closeHandlers();
        }

        //Force parse errors.  This does have side effects.
        if (debug && getConfigLocation() != null) {
            LogManager.getLogManager().readConfiguration();
        }
    }
}

From source file:edu.kit.dama.transfer.client.impl.CLUploadClient.java

/**
 * Main entry point./* w w w . ja v  a  2 s  .c  o  m*/
 *
 * @param args Command line arguments.
 */
public static void main(String[] args) {
    int result = 0;
    CLUploadClient client;
    try {
        client = new CLUploadClient(args);
        Thread.currentThread().setUncaughtExceptionHandler(client);
        client.performUpload();
        while (client.getTransferClient().isTransferRunning()) {
            try {
                Thread.sleep(DateUtils.MILLIS_PER_SECOND);
            } catch (InterruptedException ie) {
            }
        }
    } catch (TransferClientInstatiationException ie) {
        LOGGER.error("Failed to create instance of command line client", ie);
        result = 1;
    } catch (CommandLineHelpOnlyException choe) {
        result = 0;
    }
    System.exit(result);
}

From source file:edu.kit.dama.transfer.client.impl.CLDownloadClient.java

/**
 * Main entry point.//from  w  ww .  j  av  a2 s.  c  o m
 *
 * @param args Command line arguments.
 */
public static void main(String[] args) {
    int result = 0;
    CLDownloadClient client;
    try {
        client = new CLDownloadClient(args);
        Thread.currentThread().setUncaughtExceptionHandler(client);
        client.performDownload();
        while (client.getTransferClient().isTransferRunning()) {
            try {
                Thread.sleep(DateUtils.MILLIS_PER_SECOND);
            } catch (InterruptedException ie) {
            }
        }
    } catch (TransferClientInstatiationException ie) {
        LOGGER.error("Failed to create instance of command line client", ie);
        result = 1;
    } catch (CommandLineHelpOnlyException choe) {
        result = 0;
    }
    System.exit(result);
}

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  v a  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:com.pinterest.rocksplicator.Participant.java

/**
 * Start a Helix participant.// w w  w  . ja va2 s  .c  om
 * @param args command line parameters
 */
public static void main(String[] args) throws Exception {
    org.apache.log4j.Logger.getRootLogger().setLevel(Level.WARN);
    BasicConfigurator
            .configure(new ConsoleAppender(new PatternLayout("%d{HH:mm:ss.SSS} [%t] %-5p %30.30c - %m%n")));
    CommandLine cmd = processCommandLineArgs(args);
    final String zkConnectString = cmd.getOptionValue(zkServer);
    final String clusterName = cmd.getOptionValue(cluster);
    final String domainName = cmd.getOptionValue(domain);
    final String host = cmd.getOptionValue(hostAddress);
    final String port = cmd.getOptionValue(hostPort);
    final String stateModelType = cmd.getOptionValue(stateModel);
    final String postUrl = cmd.getOptionValue(configPostUrl);
    final String instanceName = host + "_" + port;

    LOG.error("Starting participant with ZK:" + zkConnectString);
    Participant participant = new Participant(zkConnectString, clusterName, instanceName, stateModelType,
            Integer.parseInt(port), postUrl);

    HelixAdmin helixAdmin = new ZKHelixAdmin(zkConnectString);
    HelixConfigScope scope = new HelixConfigScopeBuilder(HelixConfigScope.ConfigScopeProperty.PARTICIPANT)
            .forCluster(clusterName).forParticipant(instanceName).build();
    Map<String, String> properties = new HashMap<String, String>();
    properties.put("DOMAIN", domainName + ",instance=" + instanceName);
    helixAdmin.setConfig(scope, properties);

    Thread.currentThread().join();
}

From source file:com.npower.dm.util.DMUtil.java

/**
 * @param args
 */
public static void main(String[] args) {
    print(Thread.currentThread().getContextClassLoader());
}

From source file:com.wouterbreukink.onedrive.Main.java

public static void main(String[] args) throws Exception {

    // Parse command line args
    try {/*from w w w . j  av a  2s .  co  m*/
        CommandLineOpts.initialise(args);
    } catch (ParseException ex) {
        log.error("Unable to parse command line arguments - " + ex.getMessage());
        CommandLineOpts.printHelp();
        return;
    }

    if (getCommandLineOpts().help()) {
        CommandLineOpts.printHelp();
        return;
    }

    if (getCommandLineOpts().version()) {
        String version = getCommandLineOpts().getClass().getPackage().getImplementationVersion();
        log.info("onedrive-java-client version " + (version != null ? version : "DEVELOPMENT"));
        return;
    }

    // Initialise a log file (if set)
    if (getCommandLineOpts().getLogFile() != null) {
        String logFileName = LogUtils.addFileLogger(getCommandLineOpts().getLogFile());
        log.info(String.format("Writing log output to %s", logFileName));
    }

    if (getCommandLineOpts().isAuthorise()) {
        AuthorisationProvider.FACTORY.printAuthInstructions();
        return;
    }

    if (getCommandLineOpts().getLocalPath() == null || getCommandLineOpts().getRemotePath() == null
            || getCommandLineOpts().getDirection() == null) {
        log.error("Must specify --local, --remote and --direction");
        CommandLineOpts.printHelp();
        return;
    }

    // Initialise the OneDrive authorisation
    AuthorisationProvider authoriser;
    try {
        authoriser = AuthorisationProvider.FACTORY.create(getCommandLineOpts().getKeyFile());
        authoriser.getAccessToken();
    } catch (OneDriveAPIException ex) {
        log.error("Unable to authorise client: " + ex.getMessage());
        log.error("Re-run the application with --authorise");
        return;
    }

    // Initialise the providers
    OneDriveProvider api;
    FileSystemProvider fileSystem;
    if (getCommandLineOpts().isDryRun()) {
        log.warn("This is a dry run - no changes will be made");
        api = OneDriveProvider.FACTORY.readOnlyApi(authoriser);
        fileSystem = FileSystemProvider.FACTORY.readOnlyProvider();
    } else {
        api = OneDriveProvider.FACTORY.readWriteApi(authoriser);
        fileSystem = FileSystemProvider.FACTORY.readWriteProvider();
    }

    // Report on progress
    TaskReporter reporter = new TaskReporter();

    // Get the primary drive
    Drive primary = api.getDefaultDrive();

    // Report quotas
    log.info(String.format("Using drive with id '%s' (%s). Usage %s of %s (%.2f%%)", primary.getId(),
            primary.getDriveType(), readableFileSize(primary.getQuota().getUsed()),
            readableFileSize(primary.getQuota().getTotal()),
            ((double) primary.getQuota().getUsed() / primary.getQuota().getTotal()) * 100));

    // Check the given root folder
    OneDriveItem rootFolder = api.getPath(getCommandLineOpts().getRemotePath());

    if (!rootFolder.isDirectory()) {
        log.error(String.format("Specified root '%s' is not a folder", rootFolder.getFullName()));
        return;
    }

    File localRoot = new File(getCommandLineOpts().getLocalPath());

    log.info(String.format("Local folder '%s'", localRoot.getAbsolutePath()));
    log.info(String.format("Remote folder '<onedrive>%s'", rootFolder.getFullName()));

    // Start synchronisation operation at the root
    final TaskQueue queue = new TaskQueue();
    queue.add(new CheckTask(new Task.TaskOptions(queue, api, fileSystem, reporter), rootFolder, localRoot));

    // Get a bunch of threads going
    ExecutorService executorService = Executors.newFixedThreadPool(getCommandLineOpts().getThreads());

    for (int i = 0; i < getCommandLineOpts().getThreads(); i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    //noinspection InfiniteLoopStatement
                    while (true) {
                        Task taskToRun = null;
                        try {
                            taskToRun = queue.take();
                            taskToRun.run();
                        } finally {
                            if (taskToRun != null) {
                                queue.done(taskToRun);
                            }
                        }
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
    }

    queue.waitForCompletion();
    log.info("Synchronisation complete");
    reporter.report();
}

From source file:de.forsthaus.IpLocator.java

/**
 * For unit testing purposes only//from w  w w  .j  a va  2  s . c o  m
 * 
 * @param args
 */
public static void main(String args[]) {
    System.err.println("Start");
    try {

        final IpLocator ipl = IpLocator.locate("12.215.42.19");
        System.out.println("City=" + ipl.getCity());
        System.out.println("Country=" + ipl.getCountry());
        System.out.println("CountryCode=" + ipl.getCountryCode());
        System.out.println("Latitude=" + ipl.getLatitude());
        System.out.println("Longitude=" + ipl.getLongitude());
    } catch (final Exception e) {
        System.err.println(Thread.currentThread().getName() + " FEHLER - " + e);
        e.printStackTrace();
    }
}