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:cn.xyz.lcg.rocketmq.quickstart.PullScheduleConsumer.java

public static void main(String[] args) throws MQClientException {
    final MQPullConsumerScheduleService scheduleService = new MQPullConsumerScheduleService(
            "schedulerPullConsumer");

    scheduleService.setMessageModel(MessageModel.CLUSTERING);

    scheduleService.getDefaultMQPullConsumer().setNamesrvAddr("centOS1:9876");

    scheduleService.registerPullTaskCallback("simpleTest", new PullTaskCallback() {

        @Override//  ww  w .  j  ava  2s.c  o  m
        public void doPullTask(MessageQueue mq, PullTaskContext context) {
            MQPullConsumer consumer = context.getPullConsumer();
            try {

                long offset = consumer.fetchConsumeOffset(mq, false);
                if (offset < 0)
                    offset = 0;

                PullResult pullResult = consumer.pull(mq, "*", offset, 6);
                //                    System.out.println(offset + "\t" + mq + "\t" + pullResult);
                if (CollectionUtils.isNotEmpty(pullResult.getMsgFoundList())) {
                    for (MessageExt msg : pullResult.getMsgFoundList()) {
                        System.out.println(
                                Thread.currentThread().getName() + " " + new String(msg.getBody(), "UTF-8"));
                    }
                }
                switch (pullResult.getPullStatus()) {
                case FOUND:
                    break;
                case NO_MATCHED_MSG:
                    break;
                case NO_NEW_MSG:
                case OFFSET_ILLEGAL:
                    break;
                default:
                    break;
                }
                consumer.updateConsumeOffset(mq, pullResult.getNextBeginOffset());

                context.setPullNextDelayTimeMillis(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    scheduleService.start();
}

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

/**
 * The main entry point/*  w  w w .j a v a  2  s.  c o m*/
 *
 * @param args The command line argument array
 */
public static void main(String[] args) {

    int result = 0;
    GUIDownloadClient client;
    try {
        client = new GUIDownloadClient(args);
        Thread.currentThread().setUncaughtExceptionHandler(client);
        client.setVisible();
        while (client.isVisible()) {
            try {
                Thread.sleep(DateUtils.MILLIS_PER_SECOND);
            } catch (InterruptedException ie) {
            }
        }
    } catch (TransferClientInstatiationException ie) {
        LOGGER.error("Failed to instantiate GUI client", ie);
        result = 1;
    } catch (CommandLineHelpOnlyException choe) {
        result = 0;
    }
    System.exit(result);
}

From source file:com.rk.grid.cluster.slave.NodeMain.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
    String host = "localhost";
    String port = null;/*from   w ww . j ava 2  s  .com*/
    int indx = 0;
    String serviceName = null;
    System.out.println("Node bootstrap params: " + Arrays.asList(args));
    while (indx < args.length && args[indx].startsWith("-")) {
        if (args[indx].equalsIgnoreCase("-p")) {
            port = args[++indx];
            log("Port=" + port);
        } else if (args[indx].equalsIgnoreCase("-h")) {
            host = args[++indx];
            log("Host=" + host);
        } else if (args[indx].equalsIgnoreCase("-b")) {
            serviceName = args[++indx];
            log("Broker ServiceName=" + serviceName);
        }
        indx++;
    }

    if (port == null) {
        throw new RuntimeException("Port not set");
    }

    if (serviceName == null) {
        throw new RuntimeException("Broker Service Name not set");
    }

    RmiProxyFactoryBean s = new RmiProxyFactoryBean();
    s.setServiceUrl("rmi://" + host + ":" + port + "/" + serviceName);
    s.setServiceInterface(IBroker.class);
    s.afterPropertiesSet();

    IBroker<Object> broker = (IBroker<Object>) s.getObject();

    RemoteExecutorNode<Object> remoteExecutor = new RemoteExecutorNode<Object>(broker);

    GridConfig gridConfig = broker.getBrokerInfo().getConfig();

    if (gridConfig.libraryPathDefined()) {
        String libraryPath = gridConfig.getLibraryPath();
        ClassLoader loader = getClassLoader(libraryPath);
        Thread.currentThread().setContextClassLoader(loader);
    }

    InjectionInterceptor interceptor = new InjectionInterceptor();

    if (gridConfig.injectionContextDefined()) {
        String injectionContext = gridConfig.getInjectionContext();
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(injectionContext);
        interceptor.setContext(ctx);
    }

    interceptor.addBean("monitor", broker.getProgressMonitor());

    remoteExecutor.add(interceptor);

    remoteExecutor.start();
}

From source file:de.saly.elasticsearch.importer.imap.IMAPImporterCl.java

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

    if (args.length < 1) {
        System.out.println("Usage: IMAPImporterC [-e] <config-file>");
        System.exit(-1);/*from ww  w.  j  av  a2s  . c  o  m*/
    }

    String configFile = null;
    boolean embedded = false;

    if (args.length == 1) {
        configFile = args[0];
    }

    if (args.length == 2) {

        embedded = "-e".equals(args[0]);
        configFile = args[1];
    }

    System.out.println("Config File: " + configFile);
    System.out.println("Embedded: " + embedded);

    final Thread mainThread = Thread.currentThread();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {

            System.out.println("Will shutdown ...");

            IMAPImporterCl.stop();

            try {
                mainThread.join();
                System.out.println("Shudown done");
            } catch (InterruptedException e) {

            }
        }
    });

    start(configFile, embedded);
}

From source file:grails.util.GenerateUtils.java

public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        return;/*www.  j a v  a  2  s  .  c o m*/
    }

    String type = args[0];
    String domainClassName = args[1];

    ApplicationContext parent = new ClassPathXmlApplicationContext("applicationContext.xml");
    GrailsApplication application = parent.getBean("grailsApplication", DefaultGrailsApplication.class);

    GrailsDomainClass domainClass = findInApplication(application, domainClassName);

    // bootstrap application to try hibernate domain classes
    if (domainClass == null) {
        GrailsRuntimeConfigurator config = new GrailsRuntimeConfigurator(application, parent);
        config.configure(new MockServletContext());
    }

    // retry
    domainClass = findInApplication(application, domainClassName);
    if (domainClass == null) {
        LOG.info("Unable to generate [" + type + "] domain class not found for name [" + domainClassName + "]");
        System.exit(0);
    }

    try {
        GroovyClassLoader gcl = new GroovyClassLoader(Thread.currentThread().getContextClassLoader());
        GrailsTemplateGenerator generator = (GrailsTemplateGenerator) gcl.parseClass(
                gcl.getResourceAsStream(
                        "org/codehaus/groovy/grails/scaffolding/DefaultGrailsTemplateGenerator.groovy"),
                "DefaultGrailsTemplateGenerator.groovy").newInstance();
        if (!CONTROLLER.equals(type) && !VIEWS.equals(type) && !ALL.equals(type)) {
            LOG.info("Grails was unable to generate templates for unsupported type [" + type + "]");
        } else {
            if (VIEWS.equals(type) || ALL.equals(type)) {
                LOG.info("Generating views for domain class [" + domainClass.getName() + "]");
                generator.generateViews(domainClass, ".");
            }
            if (CONTROLLER.equals(type) || ALL.equals(type)) {
                LOG.info("Generating controller for domain class [" + domainClass.getName() + "]");
                generator.generateController(domainClass, ".");
            }
        }
    } catch (Throwable t) {
        LOG.info("Error during code generation: " + t.getMessage());
        LOG.error(t.getMessage(), t);
    } finally {
        System.exit(0);
    }
}

From source file:com.turbospaces.api.EmbeddedJSpaceRunner.java

/**
 * launcher method/*from w ww  . j  a v  a2s .c om*/
 * 
 * @param args
 *            [1 argument = application context path]
 * @throws Exception
 *             re-throw execution errors if any
 */
public static void main(final String... args) throws Exception {
    JVMUtil.gcOnExit();
    String appContextPath = args[0];
    if (System.getProperty(Global.IPv4) == null && System.getProperty(Global.IPv6) == null)
        System.setProperty(Global.IPv4, Boolean.TRUE.toString());
    System.setProperty(Global.CUSTOM_LOG_FACTORY, JGroupsCustomLoggerFactory.class.getName());

    LOGGER.info("Welcome to turbospaces:version = {}, build date = {}", SpaceUtility.projectVersion(),
            SpaceUtility.projecBuildTimestamp());
    LOGGER.info("{}: launching configuration {}", EmbeddedJSpaceRunner.class.getSimpleName(), appContextPath);
    AbstractXmlApplicationContext c = appContextPath.startsWith("file")
            ? new FileSystemXmlApplicationContext(appContextPath)
            : new ClassPathXmlApplicationContext(appContextPath);
    c.getBeansOfType(JSpace.class);
    c.registerShutdownHook();
    Collection<SpaceConfiguration> configurations = c.getBeansOfType(SpaceConfiguration.class).values();
    for (SpaceConfiguration spaceConfiguration : configurations)
        spaceConfiguration.joinNetwork();
    LOGGER.info("all jspaces joined network, notifying waiting threads...");
    synchronized (joinNetworkMonitor) {
        joinNetworkMonitor.notifyAll();
    }

    while (!Thread.currentThread().isInterrupted())
        synchronized (c) {
            try {
                c.wait(TimeUnit.SECONDS.toMillis(1));
            } catch (InterruptedException e) {
                LOGGER.info("got interruption signal, terminating jspaces... stack_trace = {}",
                        Throwables.getStackTraceAsString(e));
                Thread.currentThread().interrupt();
                Util.printThreads();
            }
        }

    c.destroy();
}

From source file:com.adeptj.runtime.core.Launcher.java

/**
 * Entry point for initializing the AdeptJ Runtime.
 * <p>/*from   ww  w. jav a2s .com*/
 * 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> runtimeArgs = parseArgs(args);
        Lifecycle lifecycle = new Server(runtimeArgs);
        lifecycle.start();
        Runtime.getRuntime().addShutdownHook(new ShutdownHook(lifecycle, Constants.SERVER_STOP_THREAD_NAME));
        launchBrowser(runtimeArgs);
        logger.info("AdeptJ Runtime initialized in [{}] ms!!", Times.elapsedMillis(startTime));
    } catch (Throwable th) { // NOSONAR
        logger.error("Exception while initializing AdeptJ Runtime!!", th);
        shutdownJvm();
    }
}

From source file:com.teradata.benchto.driver.DriverApp.java

public static void main(String[] args) throws Exception {
    CommandLine commandLine = processArguments(args);

    SpringApplicationBuilder applicationBuilder = new SpringApplicationBuilder(DriverApp.class).web(false)
            .properties();//from   ww w .  j  ava2 s  .c  om
    if (commandLine.hasOption("profile")) {
        applicationBuilder.profiles(commandLine.getOptionValue("profile"));
    }
    ConfigurableApplicationContext ctx = applicationBuilder.run();
    ExecutionDriver executionDriver = ctx.getBean(ExecutionDriver.class);

    Thread.currentThread().setName("main");

    try {
        executionDriver.execute();
        System.exit(0);
    } catch (Throwable e) {
        logException(e);
        System.exit(1);
    }
}

From source file:com.nubits.nubot.launch.NuBot.java

/**
 * Initialises the NuBot. Check if NuBot has valid parameters and quit if it
 * doesn't Check if NuBot is already running and Log if that is so
 *
 * @author desrever <desrever at nubits.com>
 * @param args a list of valid arguments
 */// w  w w . j av  a2s.c  om
public static void main(String args[]) {
    mainThread = Thread.currentThread();

    NuBot app = new NuBot();

    Utils.printSeparator();
    if (app.readParams(args)) {
        createShutDownHook();
        if (!Global.running) {
            app.execute(args);
        } else {
            LOG.severe("NuBot is already running. Make sure to terminate other instances.");
        }
    } else {
        System.exit(0);
    }
}

From source file:com.rk.grid.federation.FederatedCluster.java

/**
 * @param args/* w w  w  .ja  v a 2s  .  c om*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    int port = Integer.parseInt(args[0]);
    String clusterName = args[1];
    String masterBrokerServiceName = args[2];
    int masterPort = Integer.parseInt(args[3]);
    String masterHost = args[4];

    IBroker<Object> masterBroker = null;
    for (int i = 0; i < 100; i++) {
        try {
            masterBroker = getConnection(masterBrokerServiceName, masterPort, masterHost);
            if (masterBroker != null)
                break;
        } catch (RemoteLookupFailureException e) {
            if (i % 100 == 0)
                System.out.println("Sleeping....");
        }
        Thread.sleep(100);
    }

    if (masterBroker == null)
        throw new RuntimeException("Unable to find master broker " + masterBrokerServiceName);

    BrokerInfo brokerInfo = masterBroker.getBrokerInfo();
    GridConfig gridConfig = brokerInfo.getConfig();
    List<String> jvmNodeParams = masterBroker.getBrokerInfo().getJvmNodeParams();
    GridExecutorService cluster = new GridExecutorService(port, jvmNodeParams, gridConfig, clusterName);
    cluster.getBroker().unPause();

    final TaskExecutor taskExecutor = new TaskExecutor(cluster);

    final IRemoteResultsHandler<Object> callback = masterBroker.getCallback();
    IWorkQueue<Object> workQueue = masterBroker.getWorkQueue();

    ExecutorService pool = Executors.newFixedThreadPool(3);

    masterBroker.unPause();

    while (!Thread.currentThread().isInterrupted()) {
        final IExecutable<?> executable = workQueue.take();

        if (executable == null)
            continue;

        if (executable.equals(IExecutable.POISON)) {
            break;
        }

        Callable<Object> callable = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Future<ITaskResult<?>> future = taskExecutor.submit(executable);
                ITaskResult<?> iResult = future.get();

                String uid = executable.getUID();
                try {
                    callback.accept(new RemoteResult<Object>(iResult, uid));
                } catch (Throwable t) {
                    t.printStackTrace();
                    try {
                        callback.accept(new RemoteResult<Object>(
                                new RemoteExecutorException("Error execution remote task '" + uid + "'", t),
                                uid));
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                }
                return null;
            }

        };

        pool.submit(callable);
    }
    pool.shutdown();
    taskExecutor.shutdown();
    System.out.println("Finished...!");
}