Example usage for java.lang ThreadGroup getParent

List of usage examples for java.lang ThreadGroup getParent

Introduction

In this page you can find the example usage for java.lang ThreadGroup getParent.

Prototype

public final ThreadGroup getParent() 

Source Link

Document

Returns the parent of this thread group.

Usage

From source file:org.codelibs.fess.servlet.Tomcat6ConfigServlet.java

private Thread[] getThreads() {
    // Get the current thread group
    ThreadGroup tg = Thread.currentThread().getThreadGroup();
    // Find the root thread group
    while (tg.getParent() != null) {
        tg = tg.getParent();// w w w  . ja  va2 s .c  o m
    }

    int threadCountGuess = tg.activeCount() + 50;
    Thread[] threads = new Thread[threadCountGuess];
    int threadCountActual = tg.enumerate(threads);
    // Make sure we don't miss any threads
    while (threadCountActual == threadCountGuess) {
        threadCountGuess *= 2;
        threads = new Thread[threadCountGuess];
        // Note tg.enumerate(Thread[]) silently ignores any threads that
        // can't fit into the array
        threadCountActual = tg.enumerate(threads);
    }

    return threads;
}

From source file:Main.java

public ThreadGroupDemo() {
    ThreadGroup pGroup = new ThreadGroup("Parent ThreadGroup");

    ThreadGroup cGroup = new ThreadGroup(pGroup, "Child ThreadGroup");

    Thread t1 = new Thread(pGroup, this);
    System.out.println("Starting " + t1.getName());
    t1.start();//from  ww w .j  av  a2 s.  c  o  m

    Thread t2 = new Thread(cGroup, this);
    System.out.println("Starting " + t2.getName());
    t2.start();

    System.out.println("ParentThreadGroup for " + pGroup.getName() + " is " + pGroup.getParent().getName());
    System.out.println("ParentThreadGroup for " + cGroup.getName() + " is " + cGroup.getParent().getName());

}

From source file:ca.uviccscu.lp.server.main.ShutdownListener.java

public void threadReadout() {
    l.trace("Active thread readout");
    ThreadGroup tg = Thread.currentThread().getThreadGroup();
    while (tg.getParent() != null) {
        tg = tg.getParent();/*from w w w.j  a  v a 2 s.  c o  m*/
    }
    Thread[] threads = new Thread[tg.activeCount() + 1024];
    tg.enumerate(threads, true);
    //VERY BAD WAY TO STOP THREAD BUT NO CHOICE - need to release the file locks
    for (int i = 0; i < threads.length; i++) {
        Thread th = threads[i];
        if (th != null) {
            l.trace("Thread " + i + " : " + th.getName());

        }
    }
}

From source file:haven.Utils.java

public static void dumptg(ThreadGroup tg, PrintWriter out) {
    if (tg == null) {
        tg = Thread.currentThread().getThreadGroup();
        while (tg.getParent() != null)
            tg = tg.getParent();//w  w  w.j ava 2 s.c  o m
    }
    dumptg(tg, out, 0);
    out.flush();
}

From source file:ca.uviccscu.lp.server.main.ShutdownListener.java

@Deprecated
public void threadCleanup(File f) {
    while (!deleteFolder(f, false, 0, 0)) {
        l.error("Trying to stop more threads, list:");
        //List remaining threads
        ThreadGroup tg2 = Thread.currentThread().getThreadGroup();
        while (tg2.getParent() != null) {
            tg2 = tg2.getParent();/*from w  ww  .  j a  v a2  s.c o m*/
        }
        //Object o = new Object();
        //o.notifyAll();
        Thread[] threads = new Thread[tg2.activeCount() + 1024];
        tg2.enumerate(threads, true);
        //VERY BAD WAY TO STOP THREAD BUT NO CHOICE - need to release the file locks
        for (int i = 0; i < threads.length; i++) {
            Thread th = threads[i];
            if (th != null) {
                l.trace("Have thread: " + i + " : " + th.getName());
                if (th != null && th != Thread.currentThread()
                        && (AEThread2.isOurThread(th) || isAzThread(th))) {
                    l.trace("Suspending " + th.getName());
                    try {
                        th.suspend();
                        l.trace("ok");
                    } catch (SecurityException e) {
                        l.trace("Stop vetoed by SM", e);
                    }

                }
            }
        }
        for (int i = 0; i < threads.length; i++) {
            Thread th = threads[i];
            if (th != null) {
                l.trace("Have thread: " + i + " : " + th.getName());
                if (th != null && th != Thread.currentThread()
                        && (AEThread2.isOurThread(th) || isAzThread(th))) {
                    l.trace("Stopping " + th.getName());
                    try {
                        th.stop();
                        l.trace("ok");
                    } catch (SecurityException e) {
                        l.trace("Stop vetoed by SM", e);
                    }

                }
            }
        }
    }
    System.gc();
}

From source file:org.apache.atlas.web.resources.AdminResource.java

/**
 * Fetches the thread stack dump for this application.
 *
 * @return json representing the thread stack dump.
 *///from   w  w w  . j  a v  a2 s  . c  o m
@GET
@Path("stack")
@Produces(MediaType.TEXT_PLAIN)
public String getThreadDump() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> AdminResource.getThreadDump()");
    }

    ThreadGroup topThreadGroup = Thread.currentThread().getThreadGroup();

    while (topThreadGroup.getParent() != null) {
        topThreadGroup = topThreadGroup.getParent();
    }
    Thread[] threads = new Thread[topThreadGroup.activeCount()];

    int nr = topThreadGroup.enumerate(threads);
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < nr; i++) {
        builder.append(threads[i].getName()).append("\nState: ").append(threads[i].getState()).append("\n");
        String stackTrace = StringUtils.join(threads[i].getStackTrace(), "\n");
        builder.append(stackTrace);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== AdminResource.getThreadDump()");
    }

    return builder.toString();
}

From source file:org.sakaiproject.status.StatusServlet.java

protected ThreadGroup findSystemThreadGroup() throws Exception {
    // find the master threadgroup
    ThreadGroup group = Thread.currentThread().getThreadGroup();
    ThreadGroup parent = null;// w ww .  j ava2  s  .c om
    while ((parent = group.getParent()) != null) {
        group = parent;
    }
    return group;
}

From source file:org.sakaiproject.status.StatusServlet.java

protected void printThreadGroupDetails(ThreadGroup g, String indent, HttpServletResponse response)
        throws Exception {
    PrintWriter pw = response.getWriter();
    ThreadGroup parent = g.getParent();
    String parentName = "";
    if (parent != null) {
        parentName = parent.getName();/*w  ww .  j  a v a 2s . c  om*/
    }

    int threadCount = g.activeCount();
    int groupCount = g.activeGroupCount();

    pw.print(indent + g.getName() + "," + parentName + "," + threadCount + "," + groupCount + "\n");

    if (groupCount > 0) {
        ThreadGroup[] children = new ThreadGroup[groupCount];
        g.enumerate(children, false);

        for (ThreadGroup child : children) {
            if (child != null) {
                printThreadGroupDetails(child, indent + "  ", response);
            }
        }
    }
}

From source file:org.kaaproject.kaa.server.common.thrift.cli.server.BaseCliThriftService.java

/**
 * Dump service threads information./* w  w  w .  j  a  v  a 2 s.co m*/
 *
 * @param writer the writer to output threads information
 */
private void dumpThreads(PrintWriter writer) {
    writer.println("THREADS DUMP:");
    writer.println();

    ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threads = threadMxBean.dumpAllThreads(false, false);
    Map<Long, ThreadStruct> threadsMap = new HashMap<>();
    for (ThreadInfo ti : threads) {
        ThreadStruct ts = new ThreadStruct();
        ts.ti = ti;
        threadsMap.put(ti.getThreadId(), ts);
    }

    ThreadGroup root = Thread.currentThread().getThreadGroup();

    ThreadGroup parent;
    parent = root.getParent();
    while (parent != null) {
        root = parent;
        parent = parent.getParent();
    }
    allThreadsFromGroup(root, threadsMap);

    Collection<ThreadStruct> threadValues = threadsMap.values();
    List<ThreadStruct> threadList = new ArrayList<>(threadValues);

    Collections.sort(threadList);

    Map<State, Integer> threadStatistics = new LinkedHashMap<>();
    threadStatistics.put(State.NEW, 0);
    threadStatistics.put(State.RUNNABLE, 0);
    threadStatistics.put(State.BLOCKED, 0);
    threadStatistics.put(State.WAITING, 0);
    threadStatistics.put(State.TIMED_WAITING, 0);
    threadStatistics.put(State.TERMINATED, 0);
    int maxGroup = 0;
    int maxName = 0;
    for (ThreadStruct thread : threadList) {
        maxName = Math.max(thread.ti.getThreadName().length(), maxName);
        maxGroup = Math.max(thread.getGroupName().length(), maxGroup);
        int count = threadStatistics.get(thread.ti.getThreadState());
        count++;
        threadStatistics.put(thread.ti.getThreadState(), count);
    }

    StringBuffer header = new StringBuffer();
    header.append("ID");
    int idColumnLength = 4;
    int length = idColumnLength;
    header.append(createPadding(length - header.length()));
    header.append("GROUP");
    int groupColumnLength = maxGroup + 1;
    length += groupColumnLength;
    header.append(createPadding(length - header.length()));
    header.append("NAME");
    int nameColumnLength = maxName + 1;
    length += nameColumnLength;
    header.append(createPadding(length - header.length()));
    header.append("PRIORITY");
    int priorityColumnLength = 10;
    length += priorityColumnLength;
    header.append(createPadding(length - header.length()));
    header.append("STATE");
    int stateColumnLength = 14;
    length += stateColumnLength;
    header.append(createPadding(length - header.length()));
    header.append("DAEMON");
    int daemonColumnLengh = 7;
    length += daemonColumnLengh;
    header.append(createPadding(length - header.length()));
    header.append("ALIVE");
    int aliveColumnLengh = 6;
    length += aliveColumnLengh;
    header.append(createPadding(length - header.length()));
    header.append("CPU TIME (SEC)");
    int cpuTimeColumnLengh = 14;
    length += cpuTimeColumnLengh;
    header.append(createPadding(length - header.length()));
    writer.println(header);

    int maxRowLength = header.length();

    writer.println(createPadding(maxRowLength, '-'));

    NumberFormat format = new DecimalFormat("0.#");

    for (ThreadStruct thread : threadList) {
        StringBuffer row = new StringBuffer();
        row.append(thread.ti.getThreadId());
        int rowLength = idColumnLength;
        row.append(createPadding(rowLength - row.length()));
        row.append(thread.getGroupName());
        rowLength += groupColumnLength;
        row.append(createPadding(rowLength - row.length()));
        row.append(thread.ti.getThreadName());
        rowLength += nameColumnLength;
        row.append(createPadding(rowLength - row.length()));
        row.append(thread.getPriority());
        rowLength += priorityColumnLength;
        row.append(createPadding(rowLength - row.length()));
        row.append(thread.ti.getThreadState());
        rowLength += stateColumnLength;
        row.append(createPadding(rowLength - row.length()));
        row.append(thread.isDaemon());
        rowLength += daemonColumnLengh;
        row.append(createPadding(rowLength - row.length()));
        row.append(thread.isAlive());
        rowLength += aliveColumnLengh;
        row.append(createPadding(rowLength - row.length()));
        double cpuTimeSec = (double) threadMxBean.getThreadCpuTime(thread.ti.getThreadId())
                / (double) (1000 * 1000 * 1000);
        row.append(format.format(cpuTimeSec));
        writer.println(row);
    }

    writer.println(createPadding(maxRowLength, '-'));
    writer.println("SUMMARY:");
    writer.println(createPadding(maxRowLength, '-'));

    for (State state : threadStatistics.keySet()) {
        int count = threadStatistics.get(state);
        if (count > 0) {
            StringBuffer row = new StringBuffer();
            row.append(state.toString());
            row.append(createPadding(stateColumnLength - row.length()));
            row.append(count);
            writer.println(row);
        }
    }
    writer.println(createPadding(maxRowLength, '-'));
    StringBuffer row = new StringBuffer();
    row.append("TOTAL");
    row.append(createPadding(stateColumnLength - row.length()));
    row.append(threadList.size());
    writer.println(row);
    writer.println(createPadding(maxRowLength, '-'));
}

From source file:org.gldapdaemon.core.Configurator.java

public Configurator(String configPath, Properties properties, boolean userHome, byte mode) throws Exception {
    this.mode = mode;
    int i;/*  w  w  w . ja va2  s . c o m*/
    File programRootDir = null;
    if (mode == MODE_EMBEDDED) {

        // Embedded mode
        standaloneMode = false;
        config = properties;
        String workPath = getConfigProperty(WORK_DIR, null);
        workDirectory = new File(workPath);
    } else {

        // Load config
        if (configPath != null) {
            configFile = new File(configPath);
        }
        InputStream in = null;
        boolean configInClassPath = false;
        if (configFile == null || !configFile.isFile()) {
            try {
                in = Configurator.class.getResourceAsStream("/gcal-daemon.cfg");
                configInClassPath = in != null;
            } catch (Exception ignored) {
                in = null;
            }
            if (in == null) {
                System.out.println("INFO  | Searching main configuration file...");
                String path = (new File("x")).getAbsolutePath().replace('\\', '/');
                i = path.lastIndexOf('/');
                if (i > 1) {
                    i = path.lastIndexOf('/', i - 1);
                    if (i > 1) {
                        configFile = new File(path.substring(0, i), "conf/gcal-daemon.cfg");
                    }
                }
                if (configFile == null || !configFile.isFile()) {
                    configFile = new File("/usr/local/sbin/GCALDaemon/conf/gcal-daemon.cfg");
                }
                if (configFile == null || !configFile.isFile()) {
                    configFile = new File("/GCALDaemon/conf/gcal-daemon.cfg");
                }
                if (configFile == null || !configFile.isFile()) {
                    File root = new File("/");
                    String[] dirs = root.list();
                    if (dirs != null) {
                        for (i = 0; i < dirs.length; i++) {
                            configFile = new File('/' + dirs[i] + "/GCALDaemon/conf/gcal-daemon.cfg");
                            if (configFile.isFile()) {
                                break;
                            }
                        }
                    }
                }
                if (configFile == null || !configFile.isFile()) {
                    throw new FileNotFoundException("Missing main configuration file: " + configPath);
                }
                if (!userHome) {

                    // Open global config file
                    in = new FileInputStream(configFile);
                }
            }
        } else {
            if (!userHome) {
                // Open global config file
                in = new FileInputStream(configFile);
            }
        }
        standaloneMode = !configInClassPath;
        if (in != null) {

            // Load global config file
            config.load(new BufferedInputStream(in));
            in.close();
        }

        // Loading config from classpath
        if (configFile == null) {
            try {
                URL url = Configurator.class.getResource("/gcal-daemon.cfg");
                configFile = new File(url.getFile());
            } catch (Exception ignored) {
            }
        }
        programRootDir = configFile.getParentFile().getParentFile();
        System.setProperty("gldapdaemon.program.dir", programRootDir.getAbsolutePath());
        String workPath = getConfigProperty(WORK_DIR, null);
        File directory;
        if (workPath == null) {
            directory = new File(programRootDir, "work");
        } else {
            directory = new File(workPath);
        }
        if (!directory.isDirectory()) {
            if (!directory.mkdirs()) {
                directory = new File("work");
                directory.mkdirs();
            }
        }
        workDirectory = directory;

        // User-specific config file handler
        if (userHome) {
            boolean useGlobal = true;
            try {
                String home = System.getProperty("user.home", null);
                if (home != null) {
                    File userConfig = new File(home, ".gcaldaemon/gcal-daemon.cfg");
                    if (!userConfig.isFile()) {

                        // Create new user-specific config
                        File userDir = new File(home, ".gcaldaemon");
                        userDir.mkdirs();
                        copyFile(configFile, userConfig);
                        if (!userConfig.isFile()) {
                            userConfig.delete();
                            userDir.delete();
                        }
                    }
                    if (userConfig.isFile()) {

                        // Load user-specific config
                        configFile = userConfig;
                        in = new FileInputStream(configFile);
                        config.load(new BufferedInputStream(in));
                        in.close();
                        useGlobal = false;
                    }
                }
            } catch (Exception ignored) {
            }
            if (useGlobal) {

                // Load global config file
                config.load(new BufferedInputStream(in));
                in.close();
            }
        }
    }

    // Init logger
    ProgressMonitor monitor = null;
    if (standaloneMode && mode != MODE_CONFIGEDITOR) {

        // Compute log config path
        String logConfig = getConfigProperty(LOG_CONFIG, "logger-config.cfg");
        logConfig = logConfig.replace('\\', '/');
        File logConfigFile;
        if (logConfig.indexOf('/') == -1) {
            logConfigFile = new File(programRootDir, "conf/" + logConfig);
        } else {
            logConfigFile = new File(logConfig);
        }
        if (logConfigFile.isFile()) {
            String logConfigPath = logConfigFile.getAbsolutePath();
            System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
            System.setProperty("log4j.defaultInitOverride", "false");
            System.setProperty("log4j.configuration", logConfigPath);
            try {
                PropertyConfigurator.configure(logConfigPath);
            } catch (Throwable ignored) {
                ignored.printStackTrace();
            }
        }
    }
    if (mode == MODE_CONFIGEDITOR) {

        // Show monitor
        try {
            monitor = new ProgressMonitor();
            monitor.setVisible(true);
            Thread.sleep(400);
        } catch (Exception ignored) {
        }

        // Init simple logger
        try {
            System.setProperty("log4j.defaultInitOverride", "false");
            Logger root = Logger.getRootLogger();
            root.removeAllAppenders();
            root.addAppender(new ConsoleAppender(new SimpleLayout()));
            root.setLevel(Level.INFO);
        } catch (Throwable ingored) {
        }
    }

    // Disable unnecessary INFO messages of the GData API
    try {
        java.util.logging.Logger logger = java.util.logging.Logger.getLogger("com.google");
        logger.setLevel(java.util.logging.Level.WARNING);
    } catch (Throwable ingored) {
    }

    Log log = LogFactory.getLog(Configurator.class);
    log.info(VERSION + " starting...");
    if (configFile != null && log.isDebugEnabled()) {
        log.debug("Config loaded successfully (" + configFile + ").");
    }

    // Check Java version
    double jvmVersion = 1.5;
    try {
        jvmVersion = Float.valueOf(System.getProperty("java.version", "1.5").substring(0, 3)).floatValue();
    } catch (Exception ignored) {
    }
    if (jvmVersion < 1.5) {
        log.fatal("GCALDaemon requires at least Java 1.5! Current version: "
                + System.getProperty("java.version"));
        throw new Exception("Invalid JVM version!");
    }

    // Check permission
    if (workDirectory.isDirectory() && !workDirectory.canWrite()) {
        if (System.getProperty("os.name", "unknown").toLowerCase().indexOf("windows") == -1) {
            String path = workDirectory.getCanonicalPath();
            if (programRootDir != null) {
                path = programRootDir.getCanonicalPath();
            }
            log.warn("Please check the file permissions on the '" + workDirectory.getCanonicalPath()
                    + "' folder!\r\n" + "Hint: [sudo] chmod -R 777 " + path);
        }
    }

    // Disable SSL validation
    try {
        // Create a trust manager that does not validate certificate chains
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[] {
                new javax.net.ssl.X509TrustManager() {

                    public final java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public final void checkClientTrusted(java.security.cert.X509Certificate[] certs,
                            String authType) {
                    }

                    public final void checkServerTrusted(java.security.cert.X509Certificate[] certs,
                            String authType) {
                    }
                } };

        // Install the all-trusting trust manager
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Throwable ignored) {
    }

    // Replace hostname verifier
    try {
        javax.net.ssl.HostnameVerifier hv[] = new javax.net.ssl.HostnameVerifier[] {
                new javax.net.ssl.HostnameVerifier() {

                    public final boolean verify(String hostName, javax.net.ssl.SSLSession session) {
                        return true;
                    }
                } };

        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv[0]);
    } catch (Throwable ignored) {
    }

    // Setup proxy
    String proxyHost = getConfigProperty(PROXY_HOST, null);
    if (proxyHost != null) {
        String proxyPort = getConfigProperty(PROXY_PORT, null);
        if (proxyPort == null) {
            log.warn("Missing 'proxy.port' configuration property!");
        } else {

            // HTTP proxy server properties
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort);
            System.setProperty("http.proxySet", "true");

            // HTTPS proxy server properties
            System.setProperty("https.proxyHost", proxyHost);
            System.setProperty("https.proxyPort", proxyPort);
            System.setProperty("https.proxySet", "true");

            // Setup proxy credentials
            String username = getConfigProperty(PROXY_USERNAME, null);
            String encodedPassword = getConfigProperty(PROXY_PASSWORD, null);
            if (username != null) {
                if (encodedPassword == null) {
                    log.warn("Missing 'proxy.password' configuration property!");
                } else {
                    String password = StringUtils.decodePassword(encodedPassword);

                    // HTTP auth credentials
                    System.setProperty("http.proxyUser", username);
                    System.setProperty("http.proxyUserName", username);
                    System.setProperty("http.proxyPassword", password);

                    // HTTPS auth credentials
                    System.setProperty("https.proxyUser", username);
                    System.setProperty("https.proxyUserName", username);
                    System.setProperty("https.proxyPassword", password);
                }
            }
        }
    }

    // Get feed event duplication ratio
    String percent = getConfigProperty(FEED_DUPLICATION_FILTER, "70").trim();
    if (percent.endsWith("%")) {
        percent = percent.substring(0, percent.length() - 1).trim();
    }
    double ratio = Double.parseDouble(percent) / 100;
    if (ratio < 0.4) {
        ratio = 0.4;
        log.warn("The smallest enabled filter percent is '40%'!");
    } else {
        if (ratio > 1) {
            log.warn("The largest filter percent is '100%'!");
            ratio = 1;
        }
    }
    duplicationRatio = ratio;

    // Displays time zone
    log.info("Local time zone is " + TimeZone.getDefault().getDisplayName() + ".");

    // Get main thread group
    ThreadGroup mainGroup = Thread.currentThread().getThreadGroup();
    while (mainGroup.getParent() != null) {
        mainGroup = mainGroup.getParent();
    }

    // Init Gmail pool
    boolean enableLDAP = getConfigProperty(LDAP_ENABLED, false);
    if (enableLDAP) {
        gmailPool = startService(log, mainGroup, "org.gldapdaemon.core.GmailPool");
    }

    // Init LDAP listener
    if (enableLDAP) {
        contactLoader = startService(log, mainGroup, "org.gldapdaemon.core.ldap.ContactLoader");
    } else {
        if (standaloneMode) {
            log.info("LDAP server disabled.");
        }
    }

    // Clear configuration holder
    config.clear();
}