Example usage for java.lang Thread activeCount

List of usage examples for java.lang Thread activeCount

Introduction

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

Prototype

public static int activeCount() 

Source Link

Document

Returns an estimate of the number of active threads in the current thread's java.lang.ThreadGroup thread group and its subgroups.

Usage

From source file:org.apache.flink.client.minicluster.NepheleMiniCluster.java

public void start() throws Exception {

    String forkNumberString = System.getProperty("forkNumber");
    int forkNumber = -1;
    try {/*  ww  w  . j  av a  2 s . com*/
        forkNumber = Integer.parseInt(forkNumberString);
    } catch (NumberFormatException e) {
        // running inside and IDE, so the forkNumber property is not properly set
        // just ignore
    }
    if (forkNumber != -1) {
        // we are running inside a surefire/failsafe test, determine forkNumber and set
        // ports accordingly so that we can have multiple parallel instances

        jobManagerRpcPort = 1024 + forkNumber * 300;
        taskManagerRpcPort = 1024 + forkNumber * 300 + 100;
        taskManagerDataPort = 1024 + forkNumber * 300 + 200;
    }

    synchronized (startStopLock) {
        // set up the global configuration
        if (this.configDir != null) {
            GlobalConfiguration.loadConfiguration(configDir);
        } else {
            Configuration conf = getMiniclusterDefaultConfig(jobManagerRpcPort, taskManagerRpcPort,
                    taskManagerDataPort, memorySize, hdfsConfigFile, lazyMemoryAllocation,
                    defaultOverwriteFiles, defaultAlwaysCreateDirectory, taskManagerNumSlots, numTaskTracker);
            GlobalConfiguration.includeConfiguration(conf);
        }

        // force the input/output format classes to load the default values from the configuration.
        // we need to do this here, because the format classes may have been initialized before the mini cluster was started
        initializeIOFormatClasses();

        // before we start the JobManager, we need to make sure that there are no lingering IPC threads from before
        // check that all threads are done before we return
        Thread[] allThreads = new Thread[Thread.activeCount()];
        int numThreads = Thread.enumerate(allThreads);

        for (int i = 0; i < numThreads; i++) {
            Thread t = allThreads[i];
            String name = t.getName();
            if (name.startsWith("IPC")) {
                t.join();
            }
        }

        // start the job manager
        jobManager = new JobManager(ExecutionMode.LOCAL);

        waitForJobManagerToBecomeReady(numTaskTracker);
    }
}

From source file:org.alfresco.bm.mongo.MongoFactoriesTest.java

@Test
public void testSpringEnabled() throws Exception {
    // Get a DB running
    MongoDBForTestsFactory mockDBFactory = new MongoDBForTestsFactory();
    try {/* w w  w .java 2 s. c  o  m*/
        String uriWithDB = mockDBFactory.getMongoURI();
        int idx = uriWithDB.lastIndexOf("/");
        String uriWithoutDB = uriWithDB.substring(0, idx);
        System.setProperty("mongo.uri.test", uriWithoutDB);

        // Count threads
        int threadCount = Thread.activeCount();
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
                "test-MongoFactoriesTest-context.xml");
        Assert.assertTrue(Thread.activeCount() > threadCount);

        // Get the DB

        ctx.close();
        Assert.assertEquals("Not all threads killed", threadCount, Thread.activeCount());
    } finally {
        mockDBFactory.destroy();
    }
}

From source file:eu.crowdrec.contest.sender.RequestSenderORP.java

/**
 * read logFile then sends line by line to server.
 * //  w  w w  .  ja  v  a  2s  .  com
 * @param inLogFileName
 *            path to log file. That can be a zip file or text file.
 * @param outLogFile
 *            path to outLog file. The outLog file should be analyzed by the evaluator.
 *            if the filename is null; no output will be generated
 * @param serverURL
 *            URL of the server
 */
public static void sender(final String inLogFileName, final String outLogFile, final String serverURL) {

    // handle the log file
    // check type of file

    // try to read the defined logFile
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        // if outLogFile name is not null, create an output file
        if (outLogFile != null && outLogFile.length() > 0) {
            bw = new BufferedWriter(new FileWriter(new File(outLogFile), false));
        }

        // support a list of files in a directory
        File inLogFile = new File(inLogFileName);
        InputStream is;
        if (inLogFile.isFile()) {
            is = new FileInputStream(inLogFileName);
            // support gZip files
            if (inLogFile.getName().toLowerCase().endsWith(".gz")) {
                is = new GZIPInputStream(is);
            }
        } else {
            // if the input is a directory, consider all files based on a pattern
            File[] childs = inLogFile.listFiles(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String name) {
                    final String fileName = name.toLowerCase();
                    return fileName.startsWith("contest.log");
                }
            });
            if (childs == null || childs.length == 0) {
                throw new IOException("invalid inLogFileName or empty directory");
            }
            Arrays.sort(childs, new Comparator<File>() {

                @Override
                public int compare(File o1, File o2) {
                    return o1.getName().compareTo(o2.getName());
                }
            });
            Vector<InputStream> isChilds = new Vector<InputStream>();
            for (int i = 0; i < childs.length; i++) {
                InputStream tmpIS = new FileInputStream(childs[i]);
                // support gZip files
                if (childs[i].getName().toLowerCase().endsWith(".gz")) {
                    tmpIS = new GZIPInputStream(tmpIS);
                }
                isChilds.add(tmpIS);
            }
            is = new SequenceInputStream(isChilds.elements());
        }

        // read the log file line by line
        br = new BufferedReader(new InputStreamReader(is));
        try {
            for (String line = br.readLine(); line != null; line = br.readLine()) {

                // ignore invalid lines and header
                if (line.startsWith("null") || line.startsWith("#")) {
                    continue;
                }

                String[] token = parseLogLine(line);
                if (token == null) {
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    System.err.println(line);
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    System.err.println(
                            "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP");
                    continue;
                }

                // use a threadPool
                RequestSenderThread t = new RequestSenderThread(token[0], token[1], token[2], serverURL, bw);
                try {
                    // try to limit the speed of sending requests
                    if (Thread.activeCount() > 1000) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Thread.activeCount() = " + Thread.activeCount());
                        }
                        Thread.sleep(200);
                    }
                } catch (Exception e) {
                    logger.info(e.toString());
                }
                t.start();
            }

        } catch (IOException e) {
            logger.warn(e.toString(), e);
        }
    } catch (FileNotFoundException e) {
        logger.error("logFile not found e:" + e.toString());
    } catch (IOException e) {
        logger.error("reading the logFile failed e:" + e.toString());
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                logger.debug("close read-log file failed");
            }
        }
        if (bw != null) {
            try {
                // wait for ensuring that all request are finished
                // this simplifies the management of thread and worked fine for all test machines
                Thread.sleep(5000);
                bw.flush();
            } catch (Exception e) {
                logger.debug("close write-log file failed");
            }
        }
    }
}

From source file:org.wso2.carbon.oc.agent.internal.OCAgentDataExtractor.java

public int getThreadCount() {
    return Thread.activeCount();
}

From source file:com.sixt.service.framework.kafka.messaging.KafkaIntegrationTest.java

private void brutallyKillConsumer(String victimName) {
    int nbThreads = Thread.activeCount();
    Thread[] threads = new Thread[nbThreads];
    Thread.enumerate(threads);//from  ww  w.  jav  a 2 s .c o m

    for (Thread t : threads) {
        if (t.getName().equals(victimName)) {
            logger.error("BOOM: Killing consumer thread {}", victimName);
            t.stop(); // used by intention despite deprecation
        }
    }
}

From source file:org.apache.tajo.QueryTestCaseBase.java

@Before
public void printTestName() {
    /* protect a travis stalled build */
    BufferPoolMXBean direct = BufferPool.getDirectBufferPool();
    BufferPoolMXBean mapped = BufferPool.getMappedBufferPool();
    System.out.println(/*w  w  w.  jav  a2 s . c  o m*/
            String.format("Used heap: %s/%s, direct:%s/%s, mapped:%s/%s, Active Threads: %d, Run: %s.%s",
                    FileUtil.humanReadableByteCount(
                            Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(), false),
                    FileUtil.humanReadableByteCount(Runtime.getRuntime().maxMemory(), false),
                    FileUtil.humanReadableByteCount(direct.getMemoryUsed(), false),
                    FileUtil.humanReadableByteCount(direct.getTotalCapacity(), false),
                    FileUtil.humanReadableByteCount(mapped.getMemoryUsed(), false),
                    FileUtil.humanReadableByteCount(mapped.getTotalCapacity(), false), Thread.activeCount(),
                    getClass().getSimpleName(), name.getMethodName()));
}

From source file:eu.crowdrec.contest.sender.RequestSender.java

/**
 * read logFile then sends line by line to server.
 * //from ww  w.  j a v a  2s.c om
 * @param inLogFileName
 *            path to log file. That can be a zip file or text file.
 * @param outLogFile
 *            path to outLog file. The outLog file should be analyzed by the evaluator.
 *            if the filename is null; no output will be generated
 * @param serverURL
 *            URL of the server
 */
public static void sender(final String inLogFileName, final String outLogFile, final String serverURL) {

    // handle the log file
    // check type of file

    // try to read the defined logFile
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        // if outLogFile name is not null, create an output file
        if (outLogFile != null && outLogFile.length() > 0) {
            bw = new BufferedWriter(new FileWriter(new File(outLogFile), false));
        }

        // support a list of files in a directory
        File inLogFile = new File(inLogFileName);
        InputStream is;
        if (inLogFile.isFile()) {
            is = new FileInputStream(inLogFileName);
            // support gZip files
            if (inLogFile.getName().toLowerCase().endsWith(".gz")) {
                is = new GZIPInputStream(is);
            }
        } else {
            // if the input is a directory, consider all files based on a pattern
            File[] childs = inLogFile.listFiles(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String name) {
                    final String fileName = name.toLowerCase();
                    return fileName.endsWith("data.idomaar.txt.gz") || fileName.endsWith("data.idomaar.txt")
                            || fileName.endsWith(".data.gz");
                }
            });
            if (childs == null || childs.length == 0) {
                throw new IOException("invalid inLogFileName or empty directory");
            }
            Arrays.sort(childs, new Comparator<File>() {

                @Override
                public int compare(File o1, File o2) {
                    return o1.getName().compareTo(o2.getName());
                }
            });
            Vector<InputStream> isChilds = new Vector<InputStream>();
            for (int i = 0; i < childs.length; i++) {
                InputStream tmpIS = new FileInputStream(childs[i]);
                // support gZip files
                if (childs[i].getName().toLowerCase().endsWith(".gz")) {
                    tmpIS = new GZIPInputStream(tmpIS);
                }
                isChilds.add(tmpIS);
            }
            is = new SequenceInputStream(isChilds.elements());
        }

        // read the log file line by line
        br = new BufferedReader(new InputStreamReader(is));
        try {
            for (String line = br.readLine(); line != null; line = br.readLine()) {

                // ignore invalid lines and header
                if (line.startsWith("null") || line.startsWith("#")) {
                    continue;
                }

                if (useThreadPool) {
                    RequestSenderThread t = new RequestSenderThread(line, serverURL, bw);
                    try {
                        // try to limit the speed of sending requests
                        if (Thread.activeCount() > 1000) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("Thread.activeCount() = " + Thread.activeCount());
                            }
                            Thread.sleep(200);
                        }
                    } catch (Exception e) {
                        logger.info(e.toString());
                    }
                    t.start();
                } else {
                    // send parameters to http server and get response.
                    final long startTime = System.currentTimeMillis();
                    String result = HttpLib.HTTPCLIENT.equals(httpLib)
                            ? excutePostWithHttpClient(line, serverURL)
                            : excutePost(line, serverURL);

                    // analyze whether an answer is expected
                    boolean answerExpected = false;
                    if (line.contains("\"event_type\": \"recommendation_request\"")) {
                        answerExpected = true;
                    }
                    if (answerExpected) {
                        if (logger.isInfoEnabled()) {
                            logger.info("serverResponse: " + result);
                        }

                        // if the output file is not null, write the output in a synchronized way
                        if (bw != null) {
                            String[] data = LogFileUtils.extractEvaluationRelevantDataFromInputLine(line);
                            String requestId = data[0];
                            String userId = data[1];
                            String itemId = data[2];
                            String domainId = data[3];
                            String timeStamp = data[4];
                            long responseTime = System.currentTimeMillis() - startTime;
                            synchronized (bw) {
                                try {
                                    bw.write("prediction\t" + requestId + "\t" + timeStamp + "\t" + responseTime
                                            + "\t" + itemId + "\t" + userId + "\t" + domainId + "\t" + result);
                                    bw.newLine();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            logger.warn(e.toString(), e);
        }
    } catch (FileNotFoundException e) {
        logger.error("logFile not found e:" + e.toString());
    } catch (IOException e) {
        logger.error("reading the logFile failed e:" + e.toString());
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                logger.debug("close read-log file failed");
            }
        }
        if (bw != null) {
            try {
                // wait for ensuring that all request are finished
                // this simplifies the management of thread and worked fine for all test machines
                Thread.sleep(5000);
                bw.flush();
            } catch (Exception e) {
                logger.debug("close write-log file failed");
            }
        }
    }
}

From source file:com.landenlabs.all_devtool.ConsoleFragment.java

@SuppressLint("DefaultLocale")
private void updateConsole() {

    if (mSystemViews.isEmpty())
        return;/*from  w w  w.j  a  va 2 s . co m*/

    try {
        // ----- System -----
        int threadCount = Thread.activeCount();
        ApplicationInfo appInfo = getActivity().getApplicationInfo();

        mSystemViews.get(SYSTEM_PACKAGE).get(1).setText(appInfo.packageName);
        mSystemViews.get(SYSTEM_MODEL).get(1).setText(Build.MODEL);
        mSystemViews.get(SYSTEM_ANDROID).get(1).setText(Build.VERSION.RELEASE);

        if (Build.VERSION.SDK_INT >= 16) {
            int lines = 0;
            final StringBuilder permSb = new StringBuilder();
            try {
                PackageInfo pi = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(),
                        PackageManager.GET_PERMISSIONS);
                for (int i = 0; i < pi.requestedPermissions.length; i++) {
                    if ((pi.requestedPermissionsFlags[i] & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0) {
                        permSb.append(pi.requestedPermissions[i]).append("\n");
                        lines++;
                    }
                }
            } catch (Exception e) {
            }
            final int lineCnt = lines;
            mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms [press]", lines));
            mSystemViews.get(SYSTEM_PERM).get(1).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getTag() == null) {
                        String permStr = permSb.toString().replaceAll("android.permission.", "")
                                .replaceAll("\n[^\n]*permission", "");
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(lineCnt);
                    } else {
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms", lineCnt));
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(null);
                    }
                }
            });

        } else {
            String permStr = "";
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Find Loc");
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Coarse Loc");
            mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
        }

        ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        int processCnt = actMgr.getRunningAppProcesses().size();
        mSystemViews.get(SYSTEM_PROCESSES).get(1).setText(String.format("%d", consoleState.processCnt));
        mSystemViews.get(SYSTEM_PROCESSES).get(2).setText(String.format("%d", processCnt));
        // mSystemViews.get(SYSTEM_BATTERY).get(1).setText(String.format("%d%%", consoleState.batteryLevel));
        mSystemViews.get(SYSTEM_BATTERY).get(2)
                .setText(String.format("%%%d", calculateBatteryLevel(getActivity())));
        // long cpuNano = Debug.threadCpuTimeNanos();
        // mSystemViews.get(SYSTEM_CPU).get(2).setText(String.format("%d%%", cpuNano));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        // ----- Network WiFi-----

        WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {
            DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();
            mNetworkViews.get(NETWORK_WIFI_IP).get(1).setText(Formatter.formatIpAddress(dhcpInfo.ipAddress));
            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            mNetworkViews.get(NETWORK_WIFI_SPEED).get(1).setText(String.valueOf(wifiInfo.getLinkSpeed()));
            int numberOfLevels = 10;
            int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1);
            mNetworkViews.get(NETWORK_WIFI_SIGNAL).get(1)
                    .setText(String.format("%%%d", 100 * level / numberOfLevels));
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
    try {
        // ----- Network Traffic-----
        // int uid = android.os.Process.myUid();
        mNetworkViews.get(NETWORK_RCV_BYTES).get(1).setText(String.format("%d", consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(1).setText(String.format("%d", consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(1).setText(String.format("%d", consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(1).setText(String.format("%d", consoleState.netTxPacks));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes()));
        mNetworkViews.get(NETWORK_RCV_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));
        mNetworkViews.get(NETWORK_SND_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes()));
        mNetworkViews.get(NETWORK_SND_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes() - consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes() - consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netTxPacks));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // ----- Memory -----
    try {
        MemoryInfo mi = new MemoryInfo();
        ActivityManager activityManager = (ActivityManager) getActivity()
                .getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);

        long heapUsing = Debug.getNativeHeapSize();

        Date now = new Date();
        long deltaMsec = now.getTime() - consoleState.lastFreeze.getTime();

        List<TextView> timeViews = mMemoryViews.get(MEMORY_TIME);
        timeViews.get(1).setText(TIMEFORMAT.format(consoleState.lastFreeze));
        timeViews.get(2).setText(TIMEFORMAT.format(now));
        timeViews.get(3).setText(
                DateUtils.getRelativeTimeSpanString(consoleState.lastFreeze.getTime(), now.getTime(), 0));
        // timeViews.get(3).setText( String.valueOf(deltaMsec));

        List<TextView> usingViews = mMemoryViews.get(MEMORY_USING);
        usingViews.get(1).setText(String.format("%d", consoleState.usingMemory));
        usingViews.get(2).setText(String.format("%d", heapUsing));
        usingViews.get(3).setText(String.format("%d", heapUsing - consoleState.usingMemory));

        List<TextView> freeViews = mMemoryViews.get(MEMORY_FREE);
        freeViews.get(1).setText(String.format("%d", consoleState.freeMemory));
        freeViews.get(2).setText(String.format("%d", mi.availMem));
        freeViews.get(3).setText(String.format("%d", mi.availMem - consoleState.freeMemory));

        List<TextView> totalViews = mMemoryViews.get(MEMORY_TOTAL);
        if (Build.VERSION.SDK_INT >= 16) {
            totalViews.get(1).setText(String.format("%d", consoleState.totalMemory));
            totalViews.get(2).setText(String.format("%d", mi.totalMem));
            totalViews.get(3).setText(String.format("%d", mi.totalMem - consoleState.totalMemory));
        } else {
            totalViews.get(0).setVisibility(View.GONE);
            totalViews.get(1).setVisibility(View.GONE);
            totalViews.get(2).setVisibility(View.GONE);
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
}

From source file:dk.netarkivet.archive.bitarchive.distribute.IntegrityTests.java

/**
 * Verify that multiple messages sent almost simultaneously works.
 *//* ww  w.j av a2 s  .c om*/
@Test
@Ignore("FIXME")
// FIXME: test temporarily disabled
public void testLotsOfMessages() {
    MessageTestHandler handler = new MessageTestHandler();
    JMSConnectionFactory.getInstance().setListener(Channels.getTheRepos(), handler);
    JMSConnectionFactory.getInstance().setListener(Channels.getThisReposClient(), handler);

    assertTrue("File to upload must exist: " + FILE_TO_UPLOAD, FILE_TO_UPLOAD.exists());

    int beforeCount = Thread.activeCount();

    for (int i = 0; i < LARGE_MESSAGE_COUNT; ++i) {
        // System.out.println("Sending message #" + i);
        bac.get(FILENAME_TO_GET, 0);
        bac.sendUploadMessage(RemoteFileFactory.getInstance(FILE_TO_UPLOAD, true, false, true)); // only
        // first
        // upload
        // will
        // succeed
        BatchMessage bMsg = new BatchMessage(THE_BAMON, Channels.getThisReposClient(), new TestBatchJobRuns(),
                Settings.get(CommonSettings.USE_REPLICA_ID));
        bac.sendBatchJob(bMsg);
        RemoveAndGetFileMessage rMsg = new RemoveAndGetFileMessage(Channels.getTheRepos(),
                Channels.getThisReposClient(), FILENAME_TO_GET, "ONE", "FFFF", "42");
        bac.sendRemoveAndGetFileMessage(rMsg);
    }
    // System.out.println("Sending messages done");
    System.out.println("Sleeping until active threads are equal to " + beforeCount);
    long maxAllowedExecutionTime = 300000; // Only run this test for max. 5
    // minutes.
    long starttime = System.currentTimeMillis();
    while (Thread.activeCount() > beforeCount
            && System.currentTimeMillis() < starttime + maxAllowedExecutionTime) {
        // System.out.println("Active count:" + Thread.activeCount());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
    }
    if (Thread.activeCount() > beforeCount) {
        fail("Should only be " + beforeCount + ", but was " + Thread.activeCount());
    }
    System.out.println("Waiting for concurrent tasks to finish..");
    ((JMSConnectionMockupMQ) JMSConnectionFactory.getInstance()).waitForConcurrentTasksToFinish();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // ignore
    }
    System.out.println("Waiting for concurrent tasks to finish..");
    ((JMSConnectionMockupMQ) JMSConnectionFactory.getInstance()).waitForConcurrentTasksToFinish();

    // assertEquals("Number of messages received by the server", 4 *
    // LARGE_MESSAGE_COUNT, bas.getCountMessages());

    assertEquals("Expecting " + LARGE_MESSAGE_COUNT + " get messages, but got " + handler.getMsg,
            LARGE_MESSAGE_COUNT, handler.getMsg.size());
    assertEquals("Expecting " + LARGE_MESSAGE_COUNT + " upload messages, but got " + handler.uploadMsg,
            LARGE_MESSAGE_COUNT, handler.uploadMsg.size());
    assertEquals("Expecting " + LARGE_MESSAGE_COUNT + " correct messages, but got " + handler.removeMsg,
            LARGE_MESSAGE_COUNT, handler.removeMsg.size());
    assertEquals("Expecting " + LARGE_MESSAGE_COUNT + " batch reply messages, but got " + handler.batchReplyMsg,
            LARGE_MESSAGE_COUNT, handler.batchReplyMsg.size());
    assertEquals("Expecting to receive all messages", LARGE_MESSAGE_COUNT * 4, handler.getTotalCount());

    // all get's expected to succeed
    int countok = 0;

    for (int i = 0; i < LARGE_MESSAGE_COUNT; ++i) {
        GetMessage msg = handler.getMsg.get(i);

        if (msg.isOk()) {
            ++countok;
        }
    }

    assertEquals("Expected number of correct get messages, but got " + handler.getMsg, LARGE_MESSAGE_COUNT,
            countok);

    // one upload expected to succeed
    countok = 0;

    for (int i = 0; i < LARGE_MESSAGE_COUNT; ++i) {
        UploadMessage msg = handler.uploadMsg.get(i);

        if (msg.isOk()) {
            ++countok;
        }
    }

    assertEquals("Expected number of correct upload messages, but got " + handler.uploadMsg, 1, countok);

    // all batches expected to succeed
    countok = 0;

    for (int i = 0; i < LARGE_MESSAGE_COUNT; ++i) {
        BatchReplyMessage msg = handler.batchReplyMsg.get(i);

        if (msg.isOk()) {
            ++countok;
        }
    }

    assertEquals("Expected number of correct BatchReply messages, but got " + handler.batchReplyMsg,
            LARGE_MESSAGE_COUNT, countok);

    // all correct's expected to fail
    countok = 0;

    for (int i = 0; i < LARGE_MESSAGE_COUNT; ++i) {
        RemoveAndGetFileMessage msg = handler.removeMsg.get(i);

        if (!msg.isOk()) {
            ++countok;
        }
    }

    assertEquals("Expected number of failed remove messages, but got " + handler.removeMsg, LARGE_MESSAGE_COUNT,
            countok);

}

From source file:org.opencb.opencga.storage.core.variant.VariantStorageBaseTest.java

public void printActiveThreads() {
    System.out.println("=========================================");
    System.out.println("Thread.activeCount() = " + Thread.activeCount());

    Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
    Set<String> groups = allStackTraces.keySet().stream()
            .filter(t -> t.getThreadGroup() == null || !t.getThreadGroup().getName().equals("system"))
            .map(t -> String.valueOf(t.getThreadGroup())).collect(Collectors.toSet());

    for (String group : groups) {
        System.out.println("group = " + group);
        for (Map.Entry<Thread, StackTraceElement[]> entry : allStackTraces.entrySet()) {
            Thread thread = entry.getKey();
            if (String.valueOf(thread.getThreadGroup()).equals(group)) {
                System.out.println("\t[" + thread.getId() + "] " + thread.toString() + ":" + thread.getState());
            }/* w  w  w  .  jav  a2s. com*/
        }
    }
    System.out.println("=========================================");
}