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:com.adito.setup.forms.SystemInfoForm.java

/**
 * Get the number of active threads/*from   ww w  .  ja  v  a 2s. c o  m*/
 * 
 * @return active threads
 */
public String getActiveThreads() {
    try {
        return String.valueOf(Thread.activeCount());
    } catch (RuntimeException e) {
        return "unknown";
    }
}

From source file:org.bml.util.server.BServer.java

/**
* The runInvProxy class starts a new server socket and listens for
  * connections from clients. Upon recieving a connection, it starts a new
  * InvProxyThread to process the connection.
 * @param aPort The port to attach to//  w  w  w  .  j av a2s. c  o  m
 * @param aNumThreads the number of worker threads
 * @param aSleepTime sleep time in between checks
 * @param aMaxQueueLength the max requests to queue up
 * @param accessLog a Log to write access info 
 */
public void runInvProxy(int aPort, int aNumThreads, long aSleepTime, int aMaxQueueLength, Log accessLog) {
    this.accessLog = accessLog;

    if (LOG.isDebugEnabled()) {
        LOG.debug("Attempting to start server on port: " + aPort);
    }

    //Start Server
    ServerSocket myServerSocket = null;
    try {
        myServerSocket = new ServerSocket(aPort, aMaxQueueLength);
    } catch (IOException e) {
        System.out.println(e);
        return;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Server started on port: " + aPort);
    }

    //Continuously accept connections and start threads to
    //process connections.
    while (!theDone) {

        if (LOG.isDebugEnabled()) {
            LOG.debug("Ready to accept client connection");
        }

        Socket myClientSocket = null;
        try {
            myClientSocket = myServerSocket.accept();
        } catch (IOException e) {
            System.out.println("Accept Error: " + e);
            break;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Accepted connection from client: " + myClientSocket.getInetAddress()
                    + "\nStarting thread to deal with connection");
        }

        //Make sure there aren't too many active threads
        if (aNumThreads != -1) {
            while (Thread.activeCount() > aNumThreads) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Too many active threads.  Waiting " + aSleepTime
                            + "(ms) before trying to start new HitServerInvProxyThread again");
                }
                try {
                    Thread.sleep(aSleepTime);
                } catch (InterruptedException e) {
                    System.out.println(e);
                    break;
                }
            }
        }
        if (myClientSocket != null && myClientSocket.isConnected()) {
            new InvProxyThread(this, myClientSocket, this.accessLog);
        } else {
            if (LOG.isWarnEnabled()) {
                LOG.warn("Client Socket is null or not connected when starting thread");
            }
            break;
        }
    }

    //Closing socket
    if (LOG.isDebugEnabled()) {
        LOG.debug("Closing server socket.  In general, we should never get here.");
    }

    try {
        myServerSocket.close();
    } catch (IOException e) {
        System.out.println(e);
        return;
    }
}

From source file:lineage2.gameserver.network.telnet.commands.TelnetStatus.java

/**
 * Constructor for TelnetStatus./*from  ww  w.  jav  a 2  s. c  o  m*/
 */
public TelnetStatus() {
    _commands.add(new TelnetCommand("status", "s") {
        @Override
        public String getUsage() {
            return "status";
        }

        @Override
        public String handle(String[] args) {
            StringBuilder sb = new StringBuilder();
            int[] stats = World.getStats();
            sb.append("Server Status: ").append('\n');
            sb.append("Players: ................. ").append(stats[12]).append('/')
                    .append(Config.MAXIMUM_ONLINE_USERS).append('\n');
            sb.append("     Online: ............. ").append(stats[12] - stats[13]).append('\n');
            sb.append("     Offline: ............ ").append(stats[13]).append('\n');
            sb.append("     GM: ................. ").append(GmListTable.getAllGMs().size()).append('\n');
            sb.append("Objects: ................. ").append(stats[10]).append('\n');
            sb.append("Characters: .............. ").append(stats[11]).append('\n');
            sb.append("Summons: ................. ").append(stats[18]).append('\n');
            sb.append("Npcs: .................... ").append(stats[15]).append('/').append(stats[14])
                    .append('\n');
            sb.append("Monsters: ................ ").append(stats[16]).append('\n');
            sb.append("Minions: ................. ").append(stats[17]).append('\n');
            sb.append("Doors: ................... ").append(stats[19]).append('\n');
            sb.append("Items: ................... ").append(stats[20]).append('\n');
            sb.append("Reflections: ............. ").append(ReflectionManager.getInstance().getAll().length)
                    .append('\n');
            sb.append("Regions: ................. ").append(stats[0]).append('\n');
            sb.append("     Active: ............. ").append(stats[1]).append('\n');
            sb.append("     Inactive: ........... ").append(stats[2]).append('\n');
            sb.append("     Null: ............... ").append(stats[3]).append('\n');
            sb.append("Game Time: ............... ").append(getGameTime()).append('\n');
            sb.append("Real Time: ............... ").append(getCurrentTime()).append('\n');
            sb.append("Start Time: .............. ").append(getStartTime()).append('\n');
            sb.append("Uptime: .................. ").append(getUptime()).append('\n');
            sb.append("Shutdown: ................ ")
                    .append(Util.formatTime(Shutdown.getInstance().getSeconds())).append('/')
                    .append(Shutdown.getInstance().getMode()).append('\n');
            sb.append("Threads: ................. ").append(Thread.activeCount()).append('\n');
            sb.append("RAM Used: ................ ").append(StatsUtils.getMemUsedMb()).append('\n');
            return sb.toString();
        }
    });
}

From source file:org.loklak.api.admin.StatusService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization rights,
        JSONObjectWithDefault permissions) throws APIException {

    if (post.isLocalhostAccess() && OS.canExecUnix && post.get("upgrade", "").equals("true")) {
        Caretaker.upgrade(); // it's a hack to add this here, this may disappear anytime
    }/*from  ww w.j  a  va 2  s  .c  o  m*/

    final String backend = DAO.getConfig("backend", "");
    final boolean backend_push = DAO.getConfig("backend.push.enabled", false);
    JSONObject backend_status = null;
    JSONObject backend_status_index_sizes = null;
    if (backend.length() > 0 && !backend_push)
        try {
            backend_status = StatusService.status(backend);
            backend_status_index_sizes = backend_status == null ? null
                    : (JSONObject) backend_status.get("index_sizes");
        } catch (IOException e) {
        }
    long backend_messages = backend_status_index_sizes == null ? 0
            : ((Number) backend_status_index_sizes.get("messages")).longValue();
    long backend_users = backend_status_index_sizes == null ? 0
            : ((Number) backend_status_index_sizes.get("users")).longValue();
    long local_messages = DAO.countLocalMessages();
    long local_users = DAO.countLocalUsers();

    post.setResponse(response, "application/javascript");

    // generate json
    Runtime runtime = Runtime.getRuntime();
    JSONObject json = new JSONObject(true);
    JSONObject system = new JSONObject(true);
    system.put("assigned_memory", runtime.maxMemory());
    system.put("used_memory", runtime.totalMemory() - runtime.freeMemory());
    system.put("available_memory", runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory());
    system.put("cores", runtime.availableProcessors());
    system.put("threads", Thread.activeCount());
    system.put("runtime", System.currentTimeMillis() - Caretaker.startupTime);
    system.put("time_to_restart", Caretaker.upgradeTime - System.currentTimeMillis());
    system.put("load_system_average", OS.getSystemLoadAverage());
    system.put("load_system_cpu", OS.getSystemCpuLoad());
    system.put("load_process_cpu", OS.getProcessCpuLoad());
    system.put("server_threads", LoklakServer.getServerThreads());
    system.put("server_uri", LoklakServer.getServerURI());

    JSONObject index = new JSONObject(true);
    long countLocalMinMessages = DAO.countLocalMessages(60000L);
    long countLocal10MMessages = DAO.countLocalMessages(600000L);
    long countLocalHourMessages = DAO.countLocalMessages(3600000L);
    long countLocalDayMessages = DAO.countLocalMessages(86400000L);
    long countLocalWeekMessages = DAO.countLocalMessages(604800000L);
    float mps1m = countLocalMinMessages / 60f;
    float mps10m = countLocal10MMessages / 600f;
    float mps1h = countLocalHourMessages / 3600f;
    float mps1d = countLocalDayMessages / 86400f;
    float mps1w = countLocalWeekMessages / 604800f;
    index.put("mps1m", mps1m);
    index.put("mps10m", mps10m);
    index.put("mps1h", mps1h);
    index.put("mps1d", mps1d);
    index.put("mps1w", mps1w);
    index.put("mps", (int) Math.max(mps1d, Math.max(mps1h, Math.max(mps10m, mps1m)))); // best of 1d, 1h and 10m
    JSONObject messages = new JSONObject(true);
    messages.put("size", local_messages + backend_messages);
    messages.put("size_local", local_messages);
    messages.put("size_local_minute", countLocalMinMessages);
    messages.put("size_local_10minutes", countLocal10MMessages);
    messages.put("size_local_hour", countLocalHourMessages);
    messages.put("size_local_day", countLocalDayMessages);
    messages.put("size_local_week", countLocalWeekMessages);
    messages.put("size_backend", backend_messages);
    messages.put("stats", DAO.messages.getStats());
    JSONObject queue = new JSONObject(true);
    queue.put("size", QueuedIndexing.getMessageQueueSize());
    queue.put("maxSize", QueuedIndexing.getMessageQueueMaxSize());
    queue.put("clients", QueuedIndexing.getMessageQueueClients());
    messages.put("queue", queue);
    JSONObject users = new JSONObject(true);
    users.put("size", local_users + backend_users);
    users.put("size_local", local_users);
    users.put("size_backend", backend_users);
    users.put("stats", DAO.users.getStats());
    JSONObject queries = new JSONObject(true);
    queries.put("size", DAO.countLocalQueries());
    queries.put("stats", DAO.queries.getStats());
    JSONObject accounts = new JSONObject(true);
    accounts.put("size", DAO.countLocalAccounts());
    JSONObject user = new JSONObject(true);
    user.put("size", DAO.user_dump.size());
    JSONObject followers = new JSONObject(true);
    followers.put("size", DAO.followers_dump.size());
    JSONObject following = new JSONObject(true);
    following.put("size", DAO.following_dump.size());
    index.put("messages", messages);
    index.put("users", users);
    index.put("queries", queries);
    index.put("accounts", accounts);
    index.put("user", user);
    index.put("followers", followers);
    index.put("following", following);
    if (DAO.getConfig("retrieval.queries.enabled", false)) {
        List<QueryEntry> queryList = DAO.SearchLocalQueries("", 1000, "retrieval_next", "date", SortOrder.ASC,
                null, new Date(), "retrieval_next");
        index.put("queries_pending", queryList.size());
    }

    JSONObject client_info = new JSONObject(true);
    client_info.put("RemoteHost", post.getClientHost());
    client_info.put("IsLocalhost", post.isLocalhostAccess() ? "true" : "false");

    JSONObject request_header = new JSONObject(true);
    Enumeration<String> he = post.getRequest().getHeaderNames();
    while (he.hasMoreElements()) {
        String h = he.nextElement();
        request_header.put(h, post.getRequest().getHeader(h));
    }
    client_info.put("request_header", request_header);

    json.put("system", system);
    json.put("index", index);
    json.put("client_info", client_info);

    return json;
}

From source file:org.apache.bookkeeper.test.ZooKeeperUtil.java

public void sleepServer(final int seconds, final CountDownLatch l) throws InterruptedException, IOException {
    Thread[] allthreads = new Thread[Thread.activeCount()];
    Thread.enumerate(allthreads);
    for (final Thread t : allthreads) {
        if (t.getName().contains("SyncThread:0")) {
            Thread sleeper = new Thread() {
                public void run() {
                    try {
                        t.suspend();/*from w  w  w  .  j  a v a  2s  .c om*/
                        l.countDown();
                        Thread.sleep(seconds * 1000);
                        t.resume();
                    } catch (Exception e) {
                        LOG.error("Error suspending thread", e);
                    }
                }
            };
            sleeper.start();
            return;
        }
    }
    throw new IOException("ZooKeeper thread not found");
}

From source file:org.bimserver.webservices.impl.AdminServiceImpl.java

@Override
public SJavaInfo getJavaInfo() {
    SJavaInfo javaInfo = new SJavaInfo();
    javaInfo.setHeapTotal(Runtime.getRuntime().totalMemory());
    javaInfo.setHeapUsed(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
    javaInfo.setHeapFree(Runtime.getRuntime().freeMemory());
    javaInfo.setHeapMax(Runtime.getRuntime().maxMemory());
    javaInfo.setThreads(Thread.activeCount());
    javaInfo.setJavaHome(System.getProperty("java.home"));
    javaInfo.setJavaVersion(System.getProperty("java.version"));
    javaInfo.setJavaVendor(System.getProperty("java.vendor"));
    javaInfo.setJavaVendorurl(System.getProperty("java.vendor.url"));
    javaInfo.setJavavmVersion(System.getProperty("java.vm.version"));
    javaInfo.setJavavmVendor(System.getProperty("java.vm.vendor"));
    javaInfo.setJavavmName(System.getProperty("java.vm.name"));
    javaInfo.setJavaspecVersion(System.getProperty("java.specification.version"));
    javaInfo.setJavaspecVendor(System.getProperty("java.specification.vendor"));
    javaInfo.setJavaspecName(System.getProperty("java.specification.name"));
    javaInfo.setJavaClassVersion(System.getProperty("java.class.version"));

    for (String classp : System.getProperty("java.class.path").split(File.pathSeparator)) {
        javaInfo.getJavaClasspath().add(classp);
    }/*from w  w  w.j  av a 2s  . c  om*/
    for (String classp : System.getProperty("java.library.path").split(File.pathSeparator)) {
        javaInfo.getJavaLibrarypath().add(classp);
    }
    javaInfo.setJavaIoTmp(System.getProperty("java.io.tmpdir"));
    javaInfo.setJavaExtdir(System.getProperty("java.ext.dirs"));
    javaInfo.setJavaFileSeparator(System.getProperty("file.separator"));
    javaInfo.setJavaPathSeparator(System.getProperty("path.separator"));
    javaInfo.setJavaLineSeparator(System.getProperty("line.separator"));

    return javaInfo;
}

From source file:org.asamk.signal.Main.java

public static void main(String[] args) {
    // Workaround for BKS truststore
    Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 1);

    Namespace ns = parseArgs(args);
    if (ns == null) {
        System.exit(1);// w  ww .  ja  v  a2 s . com
    }

    final String username = ns.getString("username");
    Manager m;
    Signal ts;
    DBusConnection dBusConn = null;
    try {
        if (ns.getBoolean("dbus") || ns.getBoolean("dbus_system")) {
            try {
                m = null;
                int busType;
                if (ns.getBoolean("dbus_system")) {
                    busType = DBusConnection.SYSTEM;
                } else {
                    busType = DBusConnection.SESSION;
                }
                dBusConn = DBusConnection.getConnection(busType);
                ts = (Signal) dBusConn.getRemoteObject(SIGNAL_BUSNAME, SIGNAL_OBJECTPATH, Signal.class);
            } catch (DBusException e) {
                e.printStackTrace();
                if (dBusConn != null) {
                    dBusConn.disconnect();
                }
                System.exit(3);
                return;
            }
        } else {
            String settingsPath = ns.getString("config");
            if (TextUtils.isEmpty(settingsPath)) {
                settingsPath = System.getProperty("user.home") + "/.config/signal";
                if (!new File(settingsPath).exists()) {
                    String legacySettingsPath = System.getProperty("user.home") + "/.config/textsecure";
                    if (new File(legacySettingsPath).exists()) {
                        settingsPath = legacySettingsPath;
                    }
                }
            }

            m = new Manager(username, settingsPath);
            ts = m;
            if (m.userExists()) {
                try {
                    m.load();
                } catch (Exception e) {
                    System.err
                            .println("Error loading state file \"" + m.getFileName() + "\": " + e.getMessage());
                    System.exit(2);
                    return;
                }
            }
        }

        switch (ns.getString("command")) {
        case "register":
            if (dBusConn != null) {
                System.err.println("register is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.userHasKeys()) {
                m.createNewIdentity();
            }
            try {
                m.register(ns.getBoolean("voice"));
            } catch (IOException e) {
                System.err.println("Request verify error: " + e.getMessage());
                System.exit(3);
            }
            break;
        case "verify":
            if (dBusConn != null) {
                System.err.println("verify is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.userHasKeys()) {
                System.err.println("User has no keys, first call register.");
                System.exit(1);
            }
            if (m.isRegistered()) {
                System.err.println("User registration is already verified");
                System.exit(1);
            }
            try {
                m.verifyAccount(ns.getString("verificationCode"));
            } catch (IOException e) {
                System.err.println("Verify error: " + e.getMessage());
                System.exit(3);
            }
            break;
        case "link":
            if (dBusConn != null) {
                System.err.println("link is not yet implemented via dbus");
                System.exit(1);
            }

            // When linking, username is null and we always have to create keys
            m.createNewIdentity();

            String deviceName = ns.getString("name");
            if (deviceName == null) {
                deviceName = "cli";
            }
            try {
                System.out.println(m.getDeviceLinkUri());
                m.finishDeviceLink(deviceName);
                System.out.println("Associated with: " + m.getUsername());
            } catch (TimeoutException e) {
                System.err.println("Link request timed out, please try again.");
                System.exit(3);
            } catch (IOException e) {
                System.err.println("Link request error: " + e.getMessage());
                System.exit(3);
            } catch (InvalidKeyException e) {
                e.printStackTrace();
                System.exit(3);
            } catch (UserAlreadyExists e) {
                System.err.println("The user " + e.getUsername() + " already exists\nDelete \""
                        + e.getFileName() + "\" before trying again.");
                System.exit(3);
            }
            break;
        case "addDevice":
            if (dBusConn != null) {
                System.err.println("link is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            try {
                m.addDeviceLink(new URI(ns.getString("uri")));
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(3);
            } catch (InvalidKeyException e) {
                e.printStackTrace();
                System.exit(2);
            } catch (URISyntaxException e) {
                e.printStackTrace();
                System.exit(2);
            }
            break;
        case "listDevices":
            if (dBusConn != null) {
                System.err.println("listDevices is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            try {
                List<DeviceInfo> devices = m.getLinkedDevices();
                for (DeviceInfo d : devices) {
                    System.out.println("Device " + d.getId()
                            + (d.getId() == m.getDeviceId() ? " (this device)" : "") + ":");
                    System.out.println(" Name: " + d.getName());
                    System.out.println(" Created: " + d.getCreated());
                    System.out.println(" Last seen: " + d.getLastSeen());
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(3);
            }
            break;
        case "removeDevice":
            if (dBusConn != null) {
                System.err.println("removeDevice is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            try {
                int deviceId = ns.getInt("deviceId");
                m.removeLinkedDevices(deviceId);
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(3);
            }
            break;
        case "send":
            if (dBusConn == null && !m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }

            if (ns.getBoolean("endsession")) {
                if (ns.getList("recipient") == null) {
                    System.err.println("No recipients given");
                    System.err.println("Aborting sending.");
                    System.exit(1);
                }
                try {
                    ts.sendEndSessionMessage(ns.<String>getList("recipient"));
                } catch (IOException e) {
                    handleIOException(e);
                } catch (EncapsulatedExceptions e) {
                    handleEncapsulatedExceptions(e);
                } catch (AssertionError e) {
                    handleAssertionError(e);
                } catch (DBusExecutionException e) {
                    handleDBusExecutionException(e);
                } catch (UntrustedIdentityException e) {
                    e.printStackTrace();
                }
            } else {
                String messageText = ns.getString("message");
                if (messageText == null) {
                    try {
                        messageText = IOUtils.toString(System.in);
                    } catch (IOException e) {
                        System.err.println("Failed to read message from stdin: " + e.getMessage());
                        System.err.println("Aborting sending.");
                        System.exit(1);
                    }
                }

                try {
                    List<String> attachments = ns.getList("attachment");
                    if (attachments == null) {
                        attachments = new ArrayList<>();
                    }
                    if (ns.getString("group") != null) {
                        byte[] groupId = decodeGroupId(ns.getString("group"));
                        ts.sendGroupMessage(messageText, attachments, groupId);
                    } else {
                        ts.sendMessage(messageText, attachments, ns.<String>getList("recipient"));
                    }
                } catch (IOException e) {
                    handleIOException(e);
                } catch (EncapsulatedExceptions e) {
                    handleEncapsulatedExceptions(e);
                } catch (AssertionError e) {
                    handleAssertionError(e);
                } catch (GroupNotFoundException e) {
                    handleGroupNotFoundException(e);
                } catch (AttachmentInvalidException e) {
                    System.err.println("Failed to add attachment: " + e.getMessage());
                    System.err.println("Aborting sending.");
                    System.exit(1);
                } catch (DBusExecutionException e) {
                    handleDBusExecutionException(e);
                } catch (UntrustedIdentityException e) {
                    e.printStackTrace();
                }
            }

            break;
        case "receive":
            if (dBusConn != null) {
                try {
                    dBusConn.addSigHandler(Signal.MessageReceived.class,
                            new DBusSigHandler<Signal.MessageReceived>() {
                                @Override
                                public void handle(Signal.MessageReceived s) {
                                    System.out
                                            .print(String.format("Envelope from: %s\nTimestamp: %d\nBody: %s\n",
                                                    s.getSender(), s.getTimestamp(), s.getMessage()));
                                    if (s.getGroupId().length > 0) {
                                        System.out.println("Group info:");
                                        System.out.println("  Id: " + Base64.encodeBytes(s.getGroupId()));
                                    }
                                    if (s.getAttachments().size() > 0) {
                                        System.out.println("Attachments: ");
                                        for (String attachment : s.getAttachments()) {
                                            System.out.println("-  Stored plaintext in: " + attachment);
                                        }
                                    }
                                    System.out.println();
                                }
                            });
                } catch (DBusException e) {
                    e.printStackTrace();
                }
                while (true) {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        System.exit(0);
                    }
                }
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            int timeout = 60;
            if (ns.getInt("timeout") != null) {
                timeout = ns.getInt("timeout");
            }
            boolean returnOnTimeout = true;
            if (timeout < 0) {
                returnOnTimeout = false;
                timeout = 3600;
            }
            try {

                for (int i = 0; i < 10; i++) {
                    System.out.println("Numero di threads: " + Thread.activeCount());
                    m.receiveMessages(timeout, returnOnTimeout, new ReceiveMessageHandler(m));
                }

            } catch (IOException e) {
                System.err.println("Error while receiving messages: " + e.getMessage());
                System.exit(3);
            } catch (AssertionError e) {
                handleAssertionError(e);
            }
            break;
        case "quitGroup":
            if (dBusConn != null) {
                System.err.println("quitGroup is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }

            try {
                m.sendQuitGroupMessage(decodeGroupId(ns.getString("group")));
            } catch (IOException e) {
                handleIOException(e);
            } catch (EncapsulatedExceptions e) {
                handleEncapsulatedExceptions(e);
            } catch (AssertionError e) {
                handleAssertionError(e);
            } catch (GroupNotFoundException e) {
                handleGroupNotFoundException(e);
            } catch (UntrustedIdentityException e) {
                e.printStackTrace();
            }

            break;
        case "updateGroup":
            if (dBusConn != null) {
                System.err.println("updateGroup is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }

            try {
                byte[] groupId = null;
                if (ns.getString("group") != null) {
                    groupId = decodeGroupId(ns.getString("group"));
                }
                byte[] newGroupId = m.sendUpdateGroupMessage(groupId, ns.getString("name"),
                        ns.<String>getList("member"), ns.getString("avatar"));
                if (groupId == null) {
                    System.out.println("Creating new group \"" + Base64.encodeBytes(newGroupId) + "\" ");
                }
            } catch (IOException e) {
                handleIOException(e);
            } catch (AttachmentInvalidException e) {
                System.err.println("Failed to add avatar attachment for group\": " + e.getMessage());
                System.err.println("Aborting sending.");
                System.exit(1);
            } catch (GroupNotFoundException e) {
                handleGroupNotFoundException(e);
            } catch (EncapsulatedExceptions e) {
                handleEncapsulatedExceptions(e);
            } catch (UntrustedIdentityException e) {
                e.printStackTrace();
            }

            break;
        case "daemon":
            if (dBusConn != null) {
                System.err.println("Stop it.");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            DBusConnection conn = null;
            try {
                try {
                    int busType;
                    if (ns.getBoolean("system")) {
                        busType = DBusConnection.SYSTEM;
                    } else {
                        busType = DBusConnection.SESSION;
                    }
                    conn = DBusConnection.getConnection(busType);
                    conn.exportObject(SIGNAL_OBJECTPATH, m);
                    conn.requestBusName(SIGNAL_BUSNAME);
                } catch (DBusException e) {
                    e.printStackTrace();
                    System.exit(3);
                }
                try {
                    m.receiveMessages(3600, false, new DbusReceiveMessageHandler(m, conn));
                } catch (IOException e) {
                    System.err.println("Error while receiving messages: " + e.getMessage());
                    System.exit(3);
                } catch (AssertionError e) {
                    handleAssertionError(e);
                }
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }

            break;
        }
        System.exit(0);
    } finally {
        if (dBusConn != null) {
            dBusConn.disconnect();
        }
    }
}

From source file:com.supermy.flume.interceptor.RuleThreadSearchAndReplaceInterceptor.java

@Override
public List<Event> intercept(List<Event> events) {
    //todo/*from ww w  . j a  va 2  s  .  c  o  m*/
    long s = System.currentTimeMillis();

    final AtomicInteger ai = new AtomicInteger(0);

    List<Future<Event>> results = new ArrayList<Future<Event>>();

    for (final Event event : events) {
        Future<Event> future = executorService.submit(new Callable<Event>() {
            @Override
            public Event call() {
                ai.incrementAndGet();
                return intercept(event);
            }
        });

        results.add(future);
    }

    //        List<Event> out = Lists.newArrayList();
    for (Future<Event> future : results) {

        Event event = null;
        try {
            event = future.get(); //
            //        out.add(event);
            //        if (event != null) {
            //          out.add(event);
            //        }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

    long e = System.currentTimeMillis();

    logger.info("rules:{}??{}", Thread.activeCount(), ai.intValue());
    logger.info("rules:???{}", ai.intValue() / (e - s) / 1000);
    logger.info("rules:???{}", events.size() / (e - s) / 1000);

    return events;
    //    return out;
}

From source file:eu.stratosphere.client.minicluster.NepheleMiniCluster.java

public void start() throws Exception {
    synchronized (startStopLock) {
        // set up the global configuration
        if (this.configDir != null) {
            GlobalConfiguration.loadConfiguration(configDir);
        } else {/*from w w w . j a v a2s  .  c o m*/
            Configuration conf = getMiniclusterDefaultConfig(jobManagerRpcPort, taskManagerRpcPort,
                    taskManagerDataPort, memorySize, hdfsConfigFile, lazyMemoryAllocation,
                    defaultOverwriteFiles, defaultAlwaysCreateDirectory, numTaskManager);
            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(numTaskManager);
    }
}

From source file:io.bitsquare.common.util.Utilities.java

public static void printSystemLoad() {
    Runtime runtime = Runtime.getRuntime();
    long free = runtime.freeMemory() / 1024 / 1024;
    long total = runtime.totalMemory() / 1024 / 1024;
    long used = total - free;
    log.info("System load (no. threads/used memory (MB)): " + Thread.activeCount() + "/" + used);
}