Example usage for java.lang Thread setName

List of usage examples for java.lang Thread setName

Introduction

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

Prototype

public final synchronized void setName(String name) 

Source Link

Document

Changes the name of this thread to be equal to the argument name .

Usage

From source file:com.github.vatbub.awsvpnlauncher.Main.java

/**
 * Launches a new VPN server on AWS EC2 if everything is configured
 *
 * @see PropertyNotConfiguredException//from   w w w .  ja va  2  s  .c  o  m
 * @see #terminate()
 */
private static void launch() {
    File privateKey = new File(prefs.getPreference(Property.privateKeyFile));
    vpnPassword = prefs.getPreference(Property.openvpnPassword);

    if (!privateKey.exists() && !privateKey.isFile()) {
        throw new IllegalArgumentException("The file specified as " + Property.privateKeyFile.toString()
                + " does not exist or is not a file.");
    }

    FOKLogger.info(Main.class.getName(), "Preparing...");

    try {
        // Check if our security group exists already
        FOKLogger.info(Main.class.getName(), "Checking for the required security group...");
        DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest()
                .withGroupNames(securityGroupName);

        List<String> securityGroups = new ArrayList<>();
        boolean created = false; // will become true if the security group had to be created to avoid duplicate logs
        String securityGroupId;
        try {
            DescribeSecurityGroupsResult describeSecurityGroupsResult = client
                    .describeSecurityGroups(describeSecurityGroupsRequest);
            securityGroupId = describeSecurityGroupsResult.getSecurityGroups().get(0).getGroupId();
        } catch (AmazonEC2Exception e) {
            // Security group does not exist, create the security group
            created = true;
            FOKLogger.info(Main.class.getName(), "Creating the required security group...");
            CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest()
                    .withGroupName(securityGroupName).withDescription(
                            "This security group was automatically created to run a OpenVPN Access Server.");
            CreateSecurityGroupResult createSecurityGroupResult = client
                    .createSecurityGroup(createSecurityGroupRequest);

            securityGroupId = createSecurityGroupResult.getGroupId();

            IpRange ipRange = new IpRange().withCidrIp("0.0.0.0/0");
            IpPermission sshPermission1 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp")
                    .withFromPort(22).withToPort(22);
            IpPermission sshPermission2 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp")
                    .withFromPort(943).withToPort(943);
            IpPermission httpsPermission1 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp")
                    .withFromPort(443).withToPort(443);
            IpPermission httpsPermission2 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("udp")
                    .withFromPort(1194).withToPort(1194);

            AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
                    .withGroupName(securityGroupName).withIpPermissions(sshPermission1)
                    .withIpPermissions(sshPermission2).withIpPermissions(httpsPermission1)
                    .withIpPermissions(httpsPermission2);

            // retry while the security group is not yet ready
            int retries = 0;
            long lastPollTime = System.currentTimeMillis();
            boolean requestIsFailing = true;

            do {
                // we're waiting

                if (System.currentTimeMillis() - lastPollTime >= Math.pow(2, retries) * 100) {
                    retries = retries + 1;
                    lastPollTime = System.currentTimeMillis();
                    try {
                        client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
                        // no exception => we made it
                        requestIsFailing = false;
                    } catch (AmazonEC2Exception e2) {
                        FOKLogger.info(Main.class.getName(),
                                "Still waiting for the security group to be created, api error message is currently: "
                                        + e2.getMessage());
                        requestIsFailing = true;
                    }
                }
            } while (requestIsFailing);
            FOKLogger.info(Main.class.getName(), "The required security group has been successfully created!");
        }

        if (!created) {
            FOKLogger.info(Main.class.getName(), "The required security group already exists, we can continue");
        }
        securityGroups.add(securityGroupId);

        securityGroups.add(securityGroupId);

        FOKLogger.info(Main.class.getName(), "Creating the RunInstanceRequest...");
        RunInstancesRequest request = new RunInstancesRequest(getAmiId(awsRegion), 1, 1);
        request.setInstanceType(InstanceType.T2Micro);
        request.setKeyName(prefs.getPreference(Property.awsKeyPairName));
        request.setSecurityGroupIds(securityGroups);

        FOKLogger.info(Main.class.getName(), "Starting the EC2 instance...");
        RunInstancesResult result = client.runInstances(request);
        List<Instance> instances = result.getReservation().getInstances();

        // SSH config
        FOKLogger.info(Main.class.getName(), "Configuring SSH...");
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        jsch.addIdentity(privateKey.getAbsolutePath());
        int retries = 0;

        for (Instance instance : instances) {
            // write the instance id to a properties file to be able to terminate it later on again
            prefs.reload();
            if (prefs.getPreference("instanceIDs", "").equals("")) {
                prefs.setPreference("instanceIDs", instance.getInstanceId());
            } else {
                prefs.setPreference("instanceIDs",
                        prefs.getPreference("instanceIDs", "") + ";" + instance.getInstanceId());
            }

            // Connect to the instance using ssh
            FOKLogger.info(Main.class.getName(), "Waiting for the instance to boot...");

            long lastPrintTime = System.currentTimeMillis();
            DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
            List<String> instanceId = new ArrayList<>(1);
            instanceId.add(instance.getInstanceId());
            describeInstancesRequest.setInstanceIds(instanceId);
            DescribeInstancesResult describeInstancesResult;
            newInstance = instance;

            do {
                // we're waiting

                if (System.currentTimeMillis() - lastPrintTime >= Math.pow(2, retries) * 100) {
                    retries = retries + 1;
                    describeInstancesResult = client.describeInstances(describeInstancesRequest);
                    newInstance = describeInstancesResult.getReservations().get(0).getInstances().get(0);
                    lastPrintTime = System.currentTimeMillis();
                    if (newInstance.getState().getCode() != 16) {
                        FOKLogger.info(Main.class.getName(),
                                "Still waiting for the instance to boot, current instance state is "
                                        + newInstance.getState().getName());
                    }
                }
            } while (newInstance.getState().getCode() != 16);

            FOKLogger.info(Main.class.getName(), "Instance is " + newInstance.getState().getName());

            // generate the ssh ip of the instance
            String sshIp = newInstance.getPublicDnsName();

            FOKLogger.info(Main.class.getName(), "The instance id is " + newInstance.getInstanceId());
            FOKLogger.info(Main.class.getName(), "The instance ip is " + newInstance.getPublicIpAddress());
            FOKLogger.info(Main.class.getName(), "Connecting using ssh to " + sshUsername + "@" + sshIp);
            FOKLogger.info(Main.class.getName(),
                    "The instance will need some time to configure ssh on its end so some connection timeouts are normal");
            boolean retry;
            session = jsch.getSession(sshUsername, sshIp, 22);
            session.setConfig(sshConfig);
            do {
                try {
                    session.connect();
                    retry = false;
                } catch (Exception e) {
                    FOKLogger.info(Main.class.getName(), e.getClass().getName() + ": " + e.getMessage()
                            + ", retrying, Press Ctrl+C to cancel");
                    retry = true;
                }
            } while (retry);

            FOKLogger.info(Main.class.getName(),
                    "----------------------------------------------------------------------");
            FOKLogger.info(Main.class.getName(), "The following is the out- and input of the ssh session.");
            FOKLogger.info(Main.class.getName(), "Please note that out- and input may appear out of sync.");
            FOKLogger.info(Main.class.getName(),
                    "----------------------------------------------------------------------");

            PipedInputStream sshIn = new PipedInputStream();
            PipedOutputStream sshIn2 = new PipedOutputStream(sshIn);
            PrintStream sshInCommandStream = new PrintStream(sshIn2);
            Channel channel = session.openChannel("shell");
            channel.setInputStream(sshIn);
            channel.setOutputStream(new MyPrintStream());
            channel.connect();

            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("1\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("echo \"" + adminUsername + ":" + vpnPassword + "\" | sudo chpasswd\n");
            sshInCommandStream.print("exit\n");

            NullOutputStream nullOutputStream = new NullOutputStream();
            Thread watchForSSHDisconnectThread = new Thread(() -> {
                while (channel.isConnected()) {
                    nullOutputStream.write(0);
                }
                // disconnected
                cont();
            });
            watchForSSHDisconnectThread.setName("watchForSSHDisconnectThread");
            watchForSSHDisconnectThread.start();
        }
    } catch (JSchException | IOException e) {
        e.printStackTrace();
        if (session != null) {
            session.disconnect();
        }
        System.exit(1);
    }
}

From source file:org.apache.hive.spark.client.SparkSubmitSparkClient.java

@Override
protected Future<Void> launchDriver(String isTesting, RpcServer rpcServer, String clientId) throws IOException {
    Callable<Void> runnable;

    String cmd = Joiner.on(" ").join(argv);
    LOG.info("Running client driver with argv: {}", cmd);
    ProcessBuilder pb = new ProcessBuilder("sh", "-c", cmd);

    // Prevent hive configurations from being visible in Spark.
    pb.environment().remove("HIVE_HOME");
    pb.environment().remove("HIVE_CONF_DIR");
    // Add credential provider password to the child process's environment
    // In case of Spark the credential provider location is provided in the jobConf when the job is submitted
    String password = getSparkJobCredentialProviderPassword();
    if (password != null) {
        pb.environment().put(Constants.HADOOP_CREDENTIAL_PASSWORD_ENVVAR, password);
    }/*from   w  ww  . ja  va2s  . co  m*/
    if (isTesting != null) {
        pb.environment().put("SPARK_TESTING", isTesting);
    }

    final Process child = pb.start();
    String threadName = Thread.currentThread().getName();
    final List<String> childErrorLog = Collections.synchronizedList(new ArrayList<String>());
    final LogRedirector.LogSourceCallback callback = () -> isAlive;

    LogRedirector.redirect("spark-submit-stdout-redir-" + threadName,
            new LogRedirector(child.getInputStream(), LOG, callback));
    LogRedirector.redirect("spark-submit-stderr-redir-" + threadName,
            new LogRedirector(child.getErrorStream(), LOG, childErrorLog, callback));

    runnable = () -> {
        try {
            int exitCode = child.waitFor();
            if (exitCode != 0) {
                List<String> errorMessages = new ArrayList<>();
                synchronized (childErrorLog) {
                    for (String line : childErrorLog) {
                        if (StringUtils.containsIgnoreCase(line, "Error")) {
                            errorMessages.add("\"" + line + "\"");
                        }
                    }
                }

                String errStr = errorMessages.isEmpty() ? "?" : Joiner.on(',').join(errorMessages);

                rpcServer.cancelClient(clientId, new RuntimeException("spark-submit process failed "
                        + "with exit code " + exitCode + " and error " + errStr));
            }
        } catch (InterruptedException ie) {
            LOG.warn(
                    "Thread waiting on the child process (spark-submit) is interrupted, killing the child process.");
            rpcServer.cancelClient(clientId,
                    "Thread waiting on the child process (spark-submit) is interrupted");
            Thread.interrupted();
            child.destroy();
        } catch (Exception e) {
            String errMsg = "Exception while waiting for child process (spark-submit)";
            LOG.warn(errMsg, e);
            rpcServer.cancelClient(clientId, errMsg);
        }
        return null;
    };

    FutureTask<Void> futureTask = new FutureTask<>(runnable);

    Thread driverThread = new Thread(futureTask);
    driverThread.setDaemon(true);
    driverThread.setName("SparkSubmitMonitor");
    driverThread.start();

    return futureTask;
}

From source file:com.linkedin.pinot.controller.helix.SegmentStatusChecker.java

private void startThread() {
    LOGGER.info("Starting segment status checker");

    if (_executorService == null) {
        _executorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
            @Override/* w  w  w  . jav  a  2s  .  c  o m*/
            public Thread newThread(Runnable runnable) {
                Thread thread = new Thread(runnable);
                thread.setName("SegStatChecker");
                return thread;
            }
        });
        // Set up an executor that executes segment status tasks periodically
        _executorService.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                try {
                    runSegmentMetrics();
                } catch (Exception e) {
                    LOGGER.warn("Caught exception while running segment status checker", e);
                }
            }
        }, SegmentCheckerDefaultIntervalSeconds, _segmentStatusIntervalSeconds, TimeUnit.SECONDS);
    } else {
        LOGGER.warn("SegmentStatusChecker already running. Attempt to start a duplicate thread");
    }
}

From source file:mServer.crawler.sender.MediathekOrf.java

@Override
protected void addToList() {
    MSStringBuilder seite = new MSStringBuilder(Const.STRING_BUFFER_START_BUFFER);
    listeThemen.clear();//from w ww.j a  v a  2s.c o m
    meldungStart();
    if (CrawlerTool.loadLongMax()) {
        bearbeiteAdresseSendung(seite);
    }
    listeSort(listeThemen, 1);
    int maxTage = CrawlerTool.loadLongMax() ? 9 : 2;
    for (int i = 0; i < maxTage; ++i) {
        String vorTagen = getGestern(i).toLowerCase();
        bearbeiteAdresseTag("http://tvthek.orf.at/schedule/" + vorTagen, seite);
    }
    if (Config.getStop()) {
        meldungThreadUndFertig();
    } else if (listeThemen.isEmpty()) {
        meldungThreadUndFertig();
    } else {
        meldungAddMax(listeThemen.size());
        for (int t = 0; t < getMaxThreadLaufen(); ++t) {
            //new Thread(new ThemaLaden()).start();
            Thread th = new ThemaLaden();
            th.setName(SENDERNAME + t);
            th.start();
        }
    }
}

From source file:mServer.crawler.sender.MediathekZdfTivi.java

@Override
public synchronized void addToList() {
    //Theman suchen
    listeThemen.clear();//from  ww w  . ja v a  2  s.c o m
    meldungStart();
    add_1();
    add_2();
    add_3();
    if (Config.getStop()) {
        meldungThreadUndFertig();
    } else if (listeThemen.isEmpty() && listeThemen_3.isEmpty()) {
        meldungThreadUndFertig();
    } else {
        meldungAddMax(listeThemen.size() + listeThemen_3.size());
        for (int t = 0; t < getMaxThreadLaufen(); ++t) {
            Thread th = new ThemaLaden();
            th.setName(SENDERNAME + t);
            th.start();
        }
    }
}

From source file:com.wallabystreet.kinjo.common.transport.protocol.jxta.JXTAPeer.java

@Override
public void registerService(ServiceDescriptor s) throws RegistrationFailureException {

    /* Get the peer group's discovery service. */
    DiscoveryService ds = this.group.getDiscoveryService();

    /*//from   ww w .  j a  v  a  2s.c  o m
     * Obtain the module class advertisement for the requested service from
     * its service descriptor and try to publish it to the JXTA network.
     */
    ModuleClassAdvertisement mca = (ModuleClassAdvertisement) s.getProperty("transport.jxta.adv.mc");
    try {
        ds.publish(mca);
        log.debug("module class advertisement publishing (local) successful");
    } catch (IOException e) {
        String msg = "publishing of the ModuleClassAdvertisement failed";
        log.debug(msg, e);
        throw new RegistrationFailureException(e);
    }
    ds.remotePublish(mca);
    log.debug("module class advertisement publishing (remote) successful");

    /*
     * Create the pipe advertisement for the given service, respecting the
     * peer group the system is connected to.
     */
    PipeAdvertisement pa = JXTAUtilities.createPipeAdvertisement(s);
    pa.setPipeID(IDFactory.newPipeID(this.group.getPeerGroupID()));

    /*
     * Obtain the module spec advertisement for the requested service from
     * its service descriptor, add the service's pipe advertisement to it
     * and try to publish it to the JXTA network.
     */
    ModuleSpecAdvertisement msa = (ModuleSpecAdvertisement) s.getProperty("transport.jxta.adv.ms");
    msa.setPipeAdvertisement(pa);
    try {
        ds.publish(msa);
        log.debug("module spec advertisement publishing (local) successful");
    } catch (IOException e) {
        String msg = "publishing of the ModuleSpecAdvertisement failed";
        log.debug(msg, e);
        throw new RegistrationFailureException(e);
    }
    ds.remotePublish(msa);
    log.debug("module spec advertisement publishing (remote) successful");

    // deploy the service to the WS engine.
    try {
        WSEngine.getInstance().deploy(s);
    } catch (DeploymentException e) {
        log.debug("service deployment failed", e);
        throw new RegistrationFailureException(e);
    }

    /*
     * Create a listener thread for the JXTA server pipe, using a
     * ServiceHandler instance, name it and keep the object in the classes
     */
    JXTAServiceHandler h = new JXTAServiceHandler(s, pa);
    Thread handler = new Thread(h);
    handler.setName(s.getName() + " (service handler)");
    super.serviceHandlers.put(s, h);
    handler.start();
    log.debug("service registration complete");
}

From source file:org.noroomattheinn.visibletesla.AppContext.java

public Thread launchThread(Runnable r, String name) {
    Thread t = new Thread(r);
    t.setName(name == null ? ("00 VT - " + threadID++) : name);
    t.setDaemon(true);//  www .  ja  v  a  2 s .  co m
    t.start();
    threads.add(t);

    // Clean out any old terminated threads...
    Iterator<Thread> i = threads.iterator();
    while (i.hasNext()) {
        Thread cur = i.next();
        if (cur.getState() == Thread.State.TERMINATED) {
            i.remove();
        }
    }

    return t;
}

From source file:de.jackwhite20.japs.client.cache.impl.PubSubCacheImpl.java

public PubSubCacheImpl(List<ClusterServer> clusterServers) {

    super(clusterServers);

    this.executorService = Executors.newSingleThreadExecutor(r -> {
        Thread thread = Executors.defaultThreadFactory().newThread(r);
        thread.setName("PubSubCache Thread");

        return thread;
    });/*from ww w .  j a  v a 2 s  .co m*/
    this.asyncPubSubCache = new AsyncPubSubCacheImpl(executorService, this);
}

From source file:org.mobicents.servlet.restcomm.sms.smpp.SmppService.java

private void initializeSmppConnections() {
    Configuration smppConfiguration = this.configuration.subset("smpp");

    List<Object> smppConnections = smppConfiguration.getList("connections.connection.name");

    int smppConnecsSize = smppConnections.size();
    if (smppConnecsSize == 0) {
        logger.warning("No SMPP Connections defined!");
        return;/*  w  ww. j a v a  2 s.c o m*/
    }

    for (int count = 0; count < smppConnecsSize; count++) {
        String name = smppConfiguration.getString("connections.connection(" + count + ").name");
        String systemId = smppConfiguration.getString("connections.connection(" + count + ").systemid");
        String peerIp = smppConfiguration.getString("connections.connection(" + count + ").peerip");
        int peerPort = smppConfiguration.getInt("connections.connection(" + count + ").peerport");
        SmppBindType bindtype = SmppBindType
                .valueOf(smppConfiguration.getString("connections.connection(" + count + ").bindtype"));

        if (bindtype == null) {
            logger.warning("Bindtype for SMPP name=" + name + " is not specified. Using default TRANSCEIVER");
        }

        String password = smppConfiguration.getString("connections.connection(" + count + ").password");
        String systemType = smppConfiguration.getString("connections.connection(" + count + ").systemtype");

        byte interfaceVersion = smppConfiguration
                .getByte("connections.connection(" + count + ").interfaceversion");

        byte ton = smppConfiguration.getByte("connections.connection(" + count + ").ton");
        byte npi = smppConfiguration.getByte("connections.connection(" + count + ").npi");
        String range = smppConfiguration.getString("connections.connection(" + count + ").range");

        Address address = null;
        if (ton != -1 && npi != -1 && range != null) {
            address = new Address(ton, npi, range);
        }

        int windowSize = smppConfiguration.getInt("connections.connection(" + count + ").windowsize");

        long windowWaitTimeout = smppConfiguration
                .getLong("connections.connection(" + count + ").windowwaittimeout");

        long connectTimeout = smppConfiguration.getLong("connections.connection(" + count + ").connecttimeout");
        long requestExpiryTimeout = smppConfiguration
                .getLong("connections.connection(" + count + ").requestexpirytimeout");
        long windowMonitorInterval = smppConfiguration
                .getLong("connections.connection(" + count + ").windowmonitorinterval");
        boolean logBytes = smppConfiguration.getBoolean("connections.connection(" + count + ").logbytes");
        boolean countersEnabled = smppConfiguration
                .getBoolean("connections.connection(" + count + ").countersenabled");

        long enquireLinkDelay = smppConfiguration
                .getLong("connections.connection(" + count + ").enquirelinkdelay");

        Smpp smpp = new Smpp(name, systemId, peerIp, peerPort, bindtype, password, systemType, interfaceVersion,
                address, connectTimeout, windowSize, windowWaitTimeout, requestExpiryTimeout,
                windowMonitorInterval, countersEnabled, logBytes, enquireLinkDelay);

        this.smppList.add(smpp);

        if (logger.isInfoEnabled()) {
            logger.info("creating new SMPP connection " + smpp);
        }

    }

    // for monitoring thread use, it's preferable to create your own
    // instance of an executor and cast it to a ThreadPoolExecutor from
    // Executors.newCachedThreadPool() this permits exposing thinks like
    // executor.getActiveCount() via JMX possible no point renaming the
    // threads in a factory since underlying Netty framework does not easily
    // allow you to customize your thread names
    this.executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    // to enable automatic expiration of requests, a second scheduled
    // executor is required which is what a monitor task will be executed
    // with - this is probably a thread pool that can be shared with between
    // all client bootstraps
    this.monitorExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1,
            new ThreadFactory() {
                private AtomicInteger sequence = new AtomicInteger(0);

                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r);
                    t.setName("SmppServer-SessionWindowMonitorPool-" + sequence.getAndIncrement());
                    return t;
                }
            });

    // a single instance of a client bootstrap can technically be shared
    // between any sessions that are created (a session can go to any
    // different number of SMSCs) - each session created under a client
    // bootstrap will use the executor and monitorExecutor set in its
    // constructor - just be *very* careful with the "expectedSessions"
    // value to make sure it matches the actual number of total concurrent
    // open sessions you plan on handling - the underlying netty library
    // used for NIO sockets essentially uses this value as the max number of
    // threads it will ever use, despite the "max pool size", etc. set on
    // the executor passed in here

    // Setting expected session to be 25. May be this should be
    // configurable?
    this.clientBootstrap = new DefaultSmppClient(this.executor, 25, monitorExecutor);

    this.smppClientOpsThread = new SmppClientOpsThread(this.clientBootstrap, outboundInterface("udp").getPort(),
            smppMessageHandler);

    (new Thread(this.smppClientOpsThread)).start();

    for (Smpp smpp : this.smppList) {
        this.smppClientOpsThread.scheduleConnect(smpp);
    }

    if (logger.isInfoEnabled()) {
        logger.info("SMPP Service started");
    }
}

From source file:ch.usi.da.paxos.ring.ProposerRole.java

@Override
public void run() {
    ring.getNetwork().registerCallback(this);
    Thread t = new Thread(new ProposerResender(this));
    t.setName("ProposerResender");
    t.start();//w w  w.  ja v a2  s . c o m
    if (batcher != null) {
        batcher.setProposer(this);
        Thread b = new Thread(batcher);
        b.setName("BatchPolicy");
        b.start();
    }
}