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:io.adeptj.runtime.core.Launcher.java

/**
 * Entry point for initializing the AdeptJ Runtime.
 * <p>//ww  w . j  av  a  2s . c  o m
 * It does the following tasks in order.
 * <p>
 * 1. Initializes the Logback logging framework.
 * 2. Does the deployment to embedded UNDERTOW.
 * 3. Starts the OSGi Framework.
 * 4. Starts the Undertow server.
 * 5. Registers the runtime ShutdownHook.
 *
 * @param args command line arguments for the Launcher.
 */
public static void main(String[] args) {
    Thread.currentThread().setName("AdeptJ Launcher");
    long startTime = System.nanoTime();
    LogbackInitializer.init();
    Logger logger = LoggerFactory.getLogger(Launcher.class);
    try {
        pauseForDebug();
        logger.info("JRE: [{}], Version: [{}]", JAVA_RUNTIME_NAME, JAVA_RUNTIME_VERSION);
        Map<String, String> commands = parseArgs(args);
        Lifecycle lifecycle = new Server();
        lifecycle.start();
        Runtime.getRuntime().addShutdownHook(new ShutdownHook(lifecycle, SERVER_STOP_THREAD_NAME));
        launchBrowser(commands);
        logger.info("AdeptJ Runtime initialized in [{}] ms!!", Times.elapsedMillis(startTime));
    } catch (Throwable th) { // NOSONAR
        logger.error("Exception while initializing AdeptJ Runtime!!", th);
        shutdownJvm(th);
    }
}

From source file:ClassVersionInfo.java

/**
 * Usage: ClassVersionInfo class-name/*w  w w.  j  a  v  a  2 s.  co m*/
 * 
 * Locate the class name on the thread context class loader classpath and
 * print its version info.
 * 
 * @param args
 *          [0] = class-name
 */
public static void main(String[] args) throws Exception {
    if (args.length == 0)
        throw new IllegalStateException("Usage: ...ClassVersionInfo class-name");
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    ClassVersionInfo info = new ClassVersionInfo(args[0], loader);
    System.out.println(info);
}

From source file:com.clicktravel.cheddar.server.rest.application.RestApplication.java

/**
 * Starts the RestServer to listen on the given port and address combination
 *
 * @param args String arguments, {@code [context [service-port [status-port [bind-address] ] ] ]} where
 *            <ul>/* ww w.  j  a  v a2 s.c o  m*/
 *            <li>{@code context} - Name of application, defaults to {@code UNKNOWN}</li>
 *            <li>{@code service-port} - Port number for REST service endpoints, defaults to {@code 8080}</li>
 *            <li>{@code status-port} - Port number for REST status endpoints ({@code /status} and
 *            {@code /status/healthCheck}), defaults to {@code service-port + 100}</li>
 *            <li>{@code bind-address} - Local IP address to bind server to, defaults to {@code 0.0.0.0}</li>
 *            </ul>
 *
 * @throws Exception
 */
public static void main(final String... args) {
    final String context = args.length > 0 ? args[0] : "UNKNOWN";
    final int servicePort = args.length > 1 ? Integer.parseInt(args[1]) : 8080;
    final int statusPort = args.length > 2 ? Integer.parseInt(args[2]) : servicePort + 100;
    final String bindAddress = args.length > 3 ? args[3] : "0.0.0.0";
    MDC.put("context", context);
    MDC.put("hostId", System.getProperty("host.id", "UNKNOWN"));
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    final Logger logger = LoggerFactory.getLogger(RestApplication.class);
    try {
        logger.info("Java process starting");
        logger.debug(String.format("java.version:[%s] java.vendor:[%s]", System.getProperty("java.version"),
                System.getProperty("java.vendor")));
        @SuppressWarnings("resource")
        final ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        logger.debug("Finished getting ApplicationContext");
        final ApplicationLifecycleController applicationLifecycleController = applicationContext
                .getBean(ApplicationLifecycleController.class);
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            logger.info("Shutdown hook invoked - Commencing graceful termination of Java process");
            applicationLifecycleController.shutdownApplication();
            logger.info("Java process terminating");
        }));
        applicationLifecycleController.startApplication(servicePort, statusPort, bindAddress);
        Thread.currentThread().join();
    } catch (final InterruptedException e) {
        logger.info("Java process interrupted");
        System.exit(1);
    } catch (final Exception e) {
        logger.error("Error starting Java process", e);
        System.exit(1);
    }
}

From source file:io.bitsquare.seednode.SeedNodeMain.java

public static void main(String[] args) throws Exception {
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("SeedNodeMain").setDaemon(true)
            .build();//  www .  ja  va  2s.co m
    UserThread.setExecutor(Executors.newSingleThreadExecutor(threadFactory));

    // We don't want to do the full argument parsing here as that might easily change in update versions
    // So we only handle the absolute minimum which is APP_NAME, APP_DATA_DIR_KEY and USER_DATA_DIR
    BitsquareEnvironment.setDefaultAppName("Bitsquare_seednode");
    OptionParser parser = new OptionParser();
    parser.allowsUnrecognizedOptions();
    parser.accepts(AppOptionKeys.USER_DATA_DIR_KEY, description("User data directory", DEFAULT_USER_DATA_DIR))
            .withRequiredArg();
    parser.accepts(AppOptionKeys.APP_NAME_KEY, description("Application name", DEFAULT_APP_NAME))
            .withRequiredArg();

    OptionSet options;
    try {
        options = parser.parse(args);
    } catch (OptionException ex) {
        System.out.println("error: " + ex.getMessage());
        System.out.println();
        parser.printHelpOn(System.out);
        System.exit(EXIT_FAILURE);
        return;
    }
    BitsquareEnvironment bitsquareEnvironment = new BitsquareEnvironment(options);

    // need to call that before BitsquareAppMain().execute(args)
    BitsquareExecutable.initAppDir(bitsquareEnvironment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY));

    // For some reason the JavaFX launch process results in us losing the thread context class loader: reset it.
    // In order to work around a bug in JavaFX 8u25 and below, you must include the following code as the first line of your realMain method:
    Thread.currentThread().setContextClassLoader(SeedNodeMain.class.getClassLoader());

    new SeedNodeMain().execute(args);
}

From source file:io.bitsquare.statistics.StatisticsMain.java

public static void main(String[] args) throws Exception {
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("Statistics").setDaemon(true)
            .build();/*from w  w w  .j ava2 s .  c o  m*/
    UserThread.setExecutor(Executors.newSingleThreadExecutor(threadFactory));

    // We don't want to do the full argument parsing here as that might easily change in update versions
    // So we only handle the absolute minimum which is APP_NAME, APP_DATA_DIR_KEY and USER_DATA_DIR
    BitsquareEnvironment.setDefaultAppName("Bitsquare_statistics");
    OptionParser parser = new OptionParser();
    parser.allowsUnrecognizedOptions();
    parser.accepts(AppOptionKeys.USER_DATA_DIR_KEY, description("User data directory", DEFAULT_USER_DATA_DIR))
            .withRequiredArg();
    parser.accepts(AppOptionKeys.APP_NAME_KEY, description("Application name", DEFAULT_APP_NAME))
            .withRequiredArg();

    OptionSet options;
    try {
        options = parser.parse(args);
    } catch (OptionException ex) {
        System.out.println("error: " + ex.getMessage());
        System.out.println();
        parser.printHelpOn(System.out);
        System.exit(EXIT_FAILURE);
        return;
    }
    BitsquareEnvironment bitsquareEnvironment = new BitsquareEnvironment(options);

    // need to call that before BitsquareAppMain().execute(args)
    BitsquareExecutable.initAppDir(bitsquareEnvironment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY));

    // For some reason the JavaFX launch process results in us losing the thread context class loader: reset it.
    // In order to work around a bug in JavaFX 8u25 and below, you must include the following code as the first line of your realMain method:
    Thread.currentThread().setContextClassLoader(StatisticsMain.class.getClassLoader());

    new StatisticsMain().execute(args);
}

From source file:javarestart.JavaRestartLauncher.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Usage: <URL> {<MainClass>}");
        return;//from  w  ww. j ava 2s  .  c om
    }

    if (args[0].equals("fork")) {
        String[] args2 = new String[args.length - 1];
        for (int i = 0; i < args.length - 1; i++) {
            args2[i] = args[i + 1];
        }
        fork(args2);
        return;
    }

    AppClassloader loader = new AppClassloader(args[0]);
    Thread.currentThread().setContextClassLoader(loader);
    String main;
    JSONObject obj = getJSON(args[0]);
    if (args.length < 2) {
        main = (String) obj.get("main");
    } else {
        main = args[1];
    }

    String splash = (String) obj.get("splash");
    if (splash != null) {
        SplashScreen scr = SplashScreen.getSplashScreen();
        if (scr != null) {
            URL url = loader.getResource(splash);
            scr.setImageURL(url);
        }
    }

    //auto close splash after 45 seconds
    Thread splashClose = new Thread() {
        @Override
        public void run() {
            try {
                sleep(45000);
            } catch (InterruptedException e) {
            }
            SplashScreen scr = SplashScreen.getSplashScreen();
            if ((scr != null) && (scr.isVisible())) {
                scr.close();
            }
        }
    };
    splashClose.setDaemon(true);
    splashClose.start();

    Class mainClass = loader.loadClass(main);
    Method mainMethod = mainClass.getMethod("main", String[].class);
    mainMethod.setAccessible(true);
    mainMethod.invoke(null, new Object[] { new String[0] });
}

From source file:ParallelizedMatrixProduct.java

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

    System.setSecurityManager(new YesSecurityManager());

    double[][] matrix1 = new double[MATRIX_SIZE][MATRIX_SIZE];
    double[][] matrix2 = new double[MATRIX_SIZE][MATRIX_SIZE];

    for (int i = 0; i < MATRIX_SIZE; ++i)
        for (int j = 0; j < MATRIX_SIZE; ++j) {
            matrix1[i][j] = Math.round(Math.random() * MATRIX_ELEMENT_MAX_VALUE);
            matrix2[i][j] = Math.round(Math.random() * MATRIX_ELEMENT_MAX_VALUE);
        }/* ww  w . j  a  va2s .  c om*/

    ExecutorService exec = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    Future<Double>[][] futures = new Future[MATRIX_SIZE][MATRIX_SIZE];
    for (int i = 0; i < MATRIX_SIZE; ++i) {
        for (int j = 0; j < MATRIX_SIZE; ++j) {
            final double[] v1 = getRow(matrix1, i);
            final double[] v2 = getColumn(matrix2, j);

            if (i % 2 == 0) {
                futures[i][j] = exec.submit(new Callable<Double>() {
                    public Double call() {

                        RPFSessionInfo.get().put("USER", "USER FOR " + Thread.currentThread().getName());
                        RServices rp = null;
                        int replayCounter = NBR_REPLAY_ON_FAILURE;

                        while (replayCounter >= 0) {

                            try {

                                rp = (RServices) org.kchine.rpf.ServantProviderFactory.getFactory()
                                        .getServantProvider().borrowServantProxy();

                                rp.putAndAssign(new RNumeric(v1), "rv1");
                                rp.putAndAssign(new RNumeric(v2), "rv2");
                                RMatrix res = ((RMatrix) rp.getObject("rv1%*%rv2"));

                                return ((RNumeric) res.getValue()).getValue()[0];

                            } catch (TimeoutException e) {
                                e.printStackTrace();
                                return null;
                            } catch (RemoteException re) {
                                re.printStackTrace();
                                --replayCounter;

                            } finally {

                                try {
                                    if (rp != null) {
                                        ServantProviderFactory.getFactory().getServantProvider()
                                                .returnServantProxy(rp);
                                        log.info("<" + Thread.currentThread().getName()
                                                + "> returned resource : " + rp.getServantName());
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }

                        }

                        return null;

                    }
                });
            } else {
                futures[i][j] = exec.submit(new Callable<Double>() {
                    public Double call() {

                        try {
                            return vecprod(v1, v2);
                        } finally {
                            log.info("<" + Thread.currentThread().getName() + "> Java task ended successfully");
                        }
                    }
                });
            }
        }

    }

    while (true) {
        if (countDone(futures) == (MATRIX_SIZE * MATRIX_SIZE))
            break;
        try {
            Thread.sleep(20);
        } catch (Exception e) {
        }
    }

    log.info(" done --  product matrix -->");

    Double[][] matrix1_x_matrix2 = new Double[MATRIX_SIZE][MATRIX_SIZE];
    for (int i = 0; i < MATRIX_SIZE; ++i)
        for (int j = 0; j < MATRIX_SIZE; ++j)
            matrix1_x_matrix2[i][j] = futures[i][j].get();

    System.out.println(showMatrix(matrix1, "M1"));
    System.out.println(showMatrix(matrix2, "M2"));
    System.out.println(showMatrix(matrix1_x_matrix2, "M1 x M2"));

    System.exit(0);
}

From source file:com.arpnetworking.metrics.mad.Main.java

/**
 * Entry point for Metrics Aggregator Daemon (MAD).
 *
 * @param args the command line arguments
 *//*ww  w.j  a  v a  2 s . c  om*/
public static void main(final String[] args) {
    // Global initialization
    Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
        System.err.println("Unhandled exception! exception: " + throwable.toString());
        throwable.printStackTrace(System.err);
    });

    Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> LOGGER.error()
            .setMessage("Unhandled exception!").setThrowable(throwable).log());

    LOGGER.info().setMessage("Launching mad").log();

    Runtime.getRuntime().addShutdownHook(SHUTDOWN_THREAD);

    System.setProperty("org.vertx.logger-delegate-factory-class-name",
            "org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");

    // Run the tsd aggregator
    if (args.length != 1) {
        throw new RuntimeException("No configuration file specified");
    }
    LOGGER.debug().setMessage("Loading configuration").addData("file", args[0]).log();

    Optional<DynamicConfiguration> configuration = Optional.empty();
    Optional<Configurator<Main, AggregatorConfiguration>> configurator = Optional.empty();
    try {
        final File configurationFile = new File(args[0]);
        configurator = Optional.of(new Configurator<>(Main::new, AggregatorConfiguration.class));
        configuration = Optional.of(new DynamicConfiguration.Builder().setObjectMapper(OBJECT_MAPPER)
                .addSourceBuilder(getFileSourceBuilder(configurationFile))
                .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build())
                .addListener(configurator.get()).build());

        configuration.get().launch();
        // Wait for application shutdown
        SHUTDOWN_SEMAPHORE.acquire();
    } catch (final InterruptedException e) {
        throw Throwables.propagate(e);
    } finally {
        if (configurator.isPresent()) {
            configurator.get().shutdown();
        }
        if (configuration.isPresent()) {
            configuration.get().shutdown();
        }
        // Notify the shutdown that we're done
        SHUTDOWN_SEMAPHORE.release();
    }
}

From source file:com.fjn.helper.frameworkex.apache.commons.pool.connectionPool.ConnectionManager.java

public static void main(String[] args) {
    final ConnectionManager mgr = new ConnectionManager();
    mgr.connFactory = new ConnectionFactory();
    mgr.connFactory.setDriverClass("com.mysql.jdbc.Driver");
    mgr.connFactory.setPassword("mysql");
    mgr.connFactory.setUsername("mysql");
    mgr.connFactory.setUrl("url:localhost:3306"); // ?URL

    mgr.initConnectionPool(1000, 50, 5, 1000 * 60);
    mgr.pool = mgr.connPoolFactory.createPool();

    final AtomicInteger count = new AtomicInteger(0);

    int threadNum = Runtime.getRuntime().availableProcessors();
    ExecutorService client = Executors.newFixedThreadPool(threadNum);
    for (int i = 0; i < threadNum; i++) {
        client.submit(new Runnable() {
            @Override//from   w  w w  .j  a  v a 2  s.  com
            public void run() {
                while (true && count.get() < 100) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    Connection connection = null;

                    try {
                        connection = (Connection) mgr.pool.borrowObject();
                        try {

                            int value = count.incrementAndGet();
                            if (value < 100) {
                                String threadName = Thread.currentThread().getName();

                                int activeNum = mgr.pool.getNumActive();
                                int idleNum = mgr.pool.getNumIdle();
                                String content = "ThreadName: " + threadName + "\t SQL: "
                                        + "insert into tableA ( ct ) values ('" + value + "'); \t activeNum="
                                        + activeNum + "\t idleNum=" + idleNum;
                                System.out.println(content);
                            }

                        } catch (Exception e) {
                            mgr.pool.invalidateObject(connection);
                            connection = null;
                        } finally {
                            // make sure the object is returned to the pool
                            if (null != connection) {
                                mgr.pool.returnObject(connection);
                            }
                        }
                    } catch (Exception e) {
                        // failed to borrow an object
                    }

                }
            }
        });
    }
}

From source file:de.topobyte.livecg.LiveCG.java

public static void main(String[] args) {
    // @formatter:off
    Options options = new Options();
    OptionHelper.add(options, OPTION_CONFIG, true, false, "path", "config file");
    // @formatter:on

    CommandLineParser clp = new GnuParser();

    CommandLine line = null;// w  ww. j a  v a  2s .c  o m
    try {
        line = clp.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Parsing command line failed: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    StringOption config = ArgumentHelper.getString(line, OPTION_CONFIG);
    if (config.hasValue()) {
        String configPath = config.getValue();
        LiveConfig.setPath(configPath);
    }

    Configuration configuration = PreferenceManager.getConfiguration();
    String lookAndFeel = configuration.getSelectedLookAndFeel();
    if (lookAndFeel == null) {
        lookAndFeel = UIManager.getSystemLookAndFeelClassName();
    }
    try {
        UIManager.setLookAndFeel(lookAndFeel);
    } catch (Exception e) {
        logger.error("error while setting look and feel '" + lookAndFeel + "': " + e.getClass().getSimpleName()
                + ", message: " + e.getMessage());
    }

    Content content = null;
    String filename = "res/presets/Startup.geom";

    String[] extra = line.getArgs();
    if (extra.length > 0) {
        filename = extra[0];
    }

    ContentReader reader = new ContentReader();
    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
    try {
        content = reader.read(input);
    } catch (Exception e) {
        logger.info("unable to load startup geometry file", e);
        logger.info("Exception: " + e.getClass().getSimpleName());
        logger.info("Message: " + e.getMessage());
    }

    final LiveCG runner = new LiveCG();
    final Content c = content;

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            runner.setup(true, c);
        }
    });
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            runner.frame.requestFocus();
        }
    });
}