google-site-verification: google61fe8ba583a51912.html
System Monitoring Dashboard in Java

Console-Based System Monitor

Basic System Information Collector

import java.lang.management.*; import java.io.*; import java.util.*; import java.text.DecimalFormat; public class SystemMonitor { private static final DecimalFormat df = new DecimalFormat("0.00"); private static final int REFRESH_INTERVAL = 2000; // 2 seconds public static void main(String[] args) { System.out.println("Java System Monitoring Dashboard"); System.out.println("Press 'q' to quit, 'c' to clear screen"); Scanner scanner = new Scanner(System.in); Thread inputThread = new Thread(() -> { while (true) { String input = scanner.nextLine(); if ("q".equalsIgnoreCase(input)) { System.exit(0); } else if ("c".equalsIgnoreCase(input)) { clearScreen(); } } }); inputThread.setDaemon(true); inputThread.start(); // Start monitoring startMonitoring(); } private static void clearScreen() { try { if (System.getProperty("os.name").contains("Windows")) { new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); } else { new ProcessBuilder("clear").inheritIO().start().waitFor(); } } catch (Exception e) { // Fallback: print empty lines for (int i = 0; i < 50; i++) { System.out.println(); } } } private static void startMonitoring() { while (true) { displaySystemInfo(); try { Thread.sleep(REFRESH_INTERVAL); } catch (InterruptedException e) { break; } } } private static void displaySystemInfo() { StringBuilder dashboard = new StringBuilder(); dashboard.append("╔══════════════════════════════════════════════════════════════╗\n"); dashboard.append("║ SYSTEM MONITORING DASHBOARD ║\n"); dashboard.append("╠══════════════════════════════════════════════════════════════╣\n"); // CPU Information dashboard.append(getCPUInfo()); // Memory Information dashboard.append(getMemoryInfo()); // Thread Information dashboard.append(getThreadInfo()); // Operating System Information dashboard.append(getOSInfo()); // Disk Information dashboard.append(getDiskInfo()); // Network Information (basic) dashboard.append(getNetworkInfo()); dashboard.append("╚══════════════════════════════════════════════════════════════╝\n"); dashboard.append("Commands: [q] Quit | [c] Clear Screen | Refreshing every " + (REFRESH_INTERVAL/1000) + " seconds\n"); System.out.print(dashboard.toString()); } private static String getCPUInfo() { OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) osBean; double systemCpuLoad = sunOsBean.getSystemCpuLoad() * 100; double processCpuLoad = sunOsBean.getProcessCpuLoad() * 100; long availableProcessors = sunOsBean.getAvailableProcessors(); String cpuUsageBar = getProgressBar(systemCpuLoad, 100, 20); return String.format( "║ CPU Usage: %6s%% %s ║\n" + "║ Process CPU: %6s%% ║\n" + "║ Processors: %6d ║\n", df.format(systemCpuLoad), cpuUsageBar, df.format(processCpuLoad), availableProcessors ); } private static String getMemoryInfo() { OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) osBean; MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage(); MemoryUsage nonHeapUsage = memoryBean.getNonHeapMemoryUsage(); long totalPhysicalMemory = sunOsBean.getTotalPhysicalMemorySize(); long freePhysicalMemory = sunOsBean.getFreePhysicalMemorySize(); long usedPhysicalMemory = totalPhysicalMemory - freePhysicalMemory; double physicalMemoryUsage = ((double) usedPhysicalMemory / totalPhysicalMemory) * 100; String physicalMemBar = getProgressBar(physicalMemoryUsage, 100, 20); String heapMemBar = getProgressBar( ((double) heapUsage.getUsed() / heapUsage.getMax()) * 100, 100, 20); return String.format( "║ Physical Memory: %6s%% %s ║\n" + "║ Used: %s / %s ║\n" + "║ Heap Memory: %6s%% %s ║\n" + "║ Used: %s / %s ║\n" + "║ Non-Heap: %10s / %-10s ║\n", df.format(physicalMemoryUsage), physicalMemBar, formatBytes(usedPhysicalMemory), formatBytes(totalPhysicalMemory), df.format(((double) heapUsage.getUsed() / heapUsage.getMax()) * 100), heapMemBar, formatBytes(heapUsage.getUsed()), formatBytes(heapUsage.getMax()), formatBytes(nonHeapUsage.getUsed()), formatBytes(nonHeapUsage.getMax()) ); } private static String getThreadInfo() { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); int threadCount = threadBean.getThreadCount(); int peakThreadCount = threadBean.getPeakThreadCount(); long totalStartedThreadCount = threadBean.getTotalStartedThreadCount(); int daemonThreadCount = threadBean.getDaemonThreadCount(); // Find deadlocked threads long[] deadlockedThreads = threadBean.findDeadlockedThreads(); int deadlockCount = deadlockedThreads != null ? deadlockedThreads.length : 0; String deadlockStatus = deadlockCount > 0 ? "DEADLOCK DETECTED!" : "No deadlocks"; return String.format( "║ Threads: %6d ║\n" + "║ Daemon Threads: %6d ║\n" + "║ Peak Threads: %6d ║\n" + "║ Total Started: %6d ║\n" + "║ Deadlocks: %6d - %-15s ║\n", threadCount, daemonThreadCount, peakThreadCount, totalStartedThreadCount, deadlockCount, deadlockStatus ); } private static String getOSInfo() { OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); String osName = osBean.getName(); String osVersion = osBean.getVersion(); String arch = osBean.getArchitecture(); double systemLoadAverage = osBean.getSystemLoadAverage(); return String.format( "║ OS: %-40s ║\n" + "║ Version: %-40s ║\n" + "║ Architecture: %-40s ║\n" + "║ Load Average: %-40s ║\n", truncateString(osName, 40), truncateString(osVersion, 40), truncateString(arch, 40), systemLoadAverage >= 0 ? df.format(systemLoadAverage) : "N/A" ); } private static String getDiskInfo() { File[] roots = File.listRoots(); StringBuilder diskInfo = new StringBuilder(); for (File root : roots) { long totalSpace = root.getTotalSpace(); long freeSpace = root.getFreeSpace(); long usedSpace = totalSpace - freeSpace; double usagePercent = totalSpace > 0 ? ((double) usedSpace / totalSpace) * 100 : 0; String diskBar = getProgressBar(usagePercent, 100, 15); diskInfo.append(String.format( "║ Disk %s: %6s%% %s ║\n" + "║ %s / %s free ║\n", root.getPath(), df.format(usagePercent), diskBar, formatBytes(freeSpace), formatBytes(totalSpace) )); } return diskInfo.toString(); } private static String getNetworkInfo() { // Basic network info - in a real implementation, use more sophisticated monitoring Runtime runtime = Runtime.getRuntime(); try { // This is a simple approach - for real monitoring, use more robust methods String hostName = java.net.InetAddress.getLocalHost().getHostName(); return String.format("║ Hostname: %-40s ║\n", truncateString(hostName, 40)); } catch (Exception e) { return "║ Network: Unable to retrieve network info ║\n"; } } private static String getProgressBar(double value, double max, int length) { int progress = (int) ((value / max) * length); progress = Math.min(progress, length); StringBuilder bar = new StringBuilder(); bar.append("["); for (int i = 0; i < length; i++) { if (i < progress) { bar.append("█"); } else { bar.append(" "); } } bar.append("]"); return bar.toString(); } private static String formatBytes(long bytes) { if (bytes < 1024) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(1024)); String pre = "KMGTPE".charAt(exp-1) + ""; return String.format("%.1f %sB", bytes / Math.pow(1024, exp), pre); } private static String truncateString(String str, int maxLength) { if (str.length() <= maxLength) return str; return str.substring(0, maxLength - 3) + "..."; } }

Swing GUI System Monitor

Graphical Dashboard

import javax.swing.*; import javax.swing.Timer; import java.awt.*; import java.awt.event.*; import java.lang.management.*; import java.text.DecimalFormat; import java.util.*; public class SystemMonitorGUI extends JFrame { private static final DecimalFormat df = new DecimalFormat("0.00"); private static final int UPDATE_INTERVAL = 1000; // 1 second // Components private JProgressBar cpuProgressBar, memoryProgressBar, heapProgressBar; private JLabel cpuLabel, memoryLabel, heapLabel, threadLabel, osLabel; private JTextArea processListArea; private JPanel chartPanel; private java.util.List<Double> cpuHistory = new ArrayList<>(); private java.util.List<Double> memoryHistory = new ArrayList<>(); public SystemMonitorGUI() { initializeUI(); startMonitoring(); } private void initializeUI() { setTitle("Java System Monitor Dashboard"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); // Create main panels JPanel topPanel = createTopPanel(); JPanel centerPanel = createCenterPanel(); JPanel bottomPanel = createBottomPanel(); add(topPanel, BorderLayout.NORTH); add(centerPanel, BorderLayout.CENTER); add(bottomPanel, BorderLayout.SOUTH); setSize(1000, 700); setLocationRelativeTo(null); } private JPanel createTopPanel() { JPanel panel = new JPanel(new GridLayout(2, 3, 10, 10)); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); panel.setBackground(Color.WHITE); // CPU Panel JPanel cpuPanel = createMetricPanel("CPU Usage", Color.RED); cpuProgressBar = new JProgressBar(0, 100); cpuProgressBar.setStringPainted(true); cpuLabel = new JLabel("0%", SwingConstants.CENTER); cpuLabel.setFont(new Font("Arial", Font.BOLD, 16)); cpuPanel.add(cpuProgressBar); cpuPanel.add(cpuLabel); // Memory Panel JPanel memoryPanel = createMetricPanel("Physical Memory", Color.BLUE); memoryProgressBar = new JProgressBar(0, 100); memoryProgressBar.setStringPainted(true); memoryLabel = new JLabel("0%", SwingConstants.CENTER); memoryLabel.setFont(new Font("Arial", Font.BOLD, 16)); memoryPanel.add(memoryProgressBar); memoryPanel.add(memoryLabel); // Heap Memory Panel JPanel heapPanel = createMetricPanel("Heap Memory", Color.GREEN); heapProgressBar = new JProgressBar(0, 100); heapProgressBar.setStringPainted(true); heapLabel = new JLabel("0%", SwingConstants.CENTER); heapLabel.setFont(new Font("Arial", Font.BOLD, 16)); heapPanel.add(heapProgressBar); heapPanel.add(heapLabel); // Thread Info Panel JPanel threadPanel = createInfoPanel("Threads", Color.ORANGE); threadLabel = new JLabel("Loading...", SwingConstants.CENTER); threadLabel.setFont(new Font("Arial", Font.PLAIN, 12)); threadPanel.add(threadLabel); // OS Info Panel JPanel osPanel = createInfoPanel("Operating System", Color.MAGENTA); osLabel = new JLabel("Loading...", SwingConstants.CENTER); osLabel.setFont(new Font("Arial", Font.PLAIN, 12)); osPanel.add(osLabel); // System Load Panel JPanel loadPanel = createInfoPanel("System Load", Color.CYAN); JLabel loadLabel = new JLabel("Loading...", SwingConstants.CENTER); loadLabel.setFont(new Font("Arial", Font.PLAIN, 12)); loadPanel.add(loadLabel); panel.add(cpuPanel); panel.add(memoryPanel); panel.add(heapPanel); panel.add(threadPanel); panel.add(osPanel); panel.add(loadPanel); return panel; } private JPanel createMetricPanel(String title, Color color) { JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createLineBorder(color, 2), title)); JLabel titleLabel = new JLabel(title, SwingConstants.CENTER); titleLabel.setFont(new Font("Arial", Font.BOLD, 14)); titleLabel.setForeground(color); panel.add(titleLabel, BorderLayout.NORTH); return panel; } private JPanel createInfoPanel(String title, Color color) { JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createLineBorder(color, 2), title)); return panel; } private JPanel createCenterPanel() { JPanel panel = new JPanel(new GridLayout(1, 2, 10, 10)); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // Process List JPanel processPanel = new JPanel(new BorderLayout()); processPanel.setBorder(BorderFactory.createTitledBorder("Running Processes")); processListArea = new JTextArea(); processListArea.setEditable(false); processListArea.setFont(new Font("Monospaced", Font.PLAIN, 12)); JScrollPane processScrollPane = new JScrollPane(processListArea); processPanel.add(processScrollPane, BorderLayout.CENTER); // Charts Panel JPanel chartsPanel = new JPanel(new BorderLayout()); chartsPanel.setBorder(BorderFactory.createTitledBorder("Performance Charts")); chartPanel = new ChartPanel(); chartsPanel.add(chartPanel, BorderLayout.CENTER); panel.add(processPanel); panel.add(chartsPanel); return panel; } private JPanel createBottomPanel() { JPanel panel = new JPanel(new FlowLayout()); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JButton refreshButton = new JButton("Refresh Now"); JButton exportButton = new JButton("Export Report"); JButton settingsButton = new JButton("Settings"); refreshButton.addActionListener(e -> updateSystemInfo()); exportButton.addActionListener(e -> exportReport()); settingsButton.addActionListener(e -> showSettings()); panel.add(refreshButton); panel.add(exportButton); panel.add(settingsButton); return panel; } private void startMonitoring() { Timer timer = new Timer(UPDATE_INTERVAL, e -> updateSystemInfo()); timer.start(); } private void updateSystemInfo() { // Update CPU Info updateCPUInfo(); // Update Memory Info updateMemoryInfo(); // Update Thread Info updateThreadInfo(); // Update OS Info updateOSInfo(); // Update Process List updateProcessList(); // Update Charts updateCharts(); // Repaint the chart chartPanel.repaint(); } private void updateCPUInfo() { try { OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) osBean; double systemCpuLoad = sunOsBean.getSystemCpuLoad() * 100; cpuProgressBar.setValue((int) systemCpuLoad); cpuLabel.setText(df.format(systemCpuLoad) + "%"); // Add to history for chart cpuHistory.add(systemCpuLoad); if (cpuHistory.size() > 50) { cpuHistory.remove(0); } } catch (Exception e) { cpuLabel.setText("N/A"); } } private void updateMemoryInfo() { try { OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) osBean; long totalPhysicalMemory = sunOsBean.getTotalPhysicalMemorySize(); long freePhysicalMemory = sunOsBean.getFreePhysicalMemorySize(); long usedPhysicalMemory = totalPhysicalMemory - freePhysicalMemory; double physicalMemoryUsage = ((double) usedPhysicalMemory / totalPhysicalMemory) * 100; memoryProgressBar.setValue((int) physicalMemoryUsage); memoryLabel.setText(df.format(physicalMemoryUsage) + "%"); // Update heap memory MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage(); double heapUsagePercent = ((double) heapUsage.getUsed() / heapUsage.getMax()) * 100; heapProgressBar.setValue((int) heapUsagePercent); heapLabel.setText(df.format(heapUsagePercent) + "%"); // Add to history for chart memoryHistory.add(physicalMemoryUsage); if (memoryHistory.size() > 50) { memoryHistory.remove(0); } } catch (Exception e) { memoryLabel.setText("N/A"); heapLabel.setText("N/A"); } } private void updateThreadInfo() { try { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); int threadCount = threadBean.getThreadCount(); int peakThreadCount = threadBean.getPeakThreadCount(); int daemonThreadCount = threadBean.getDaemonThreadCount(); long[] deadlockedThreads = threadBean.findDeadlockedThreads(); int deadlockCount = deadlockedThreads != null ? deadlockedThreads.length : 0; String threadInfo = String.format( "<html><center>Current: %d<br>Peak: %d<br>Daemon: %d<br>Deadlocks: %d</center></html>", threadCount, peakThreadCount, daemonThreadCount, deadlockCount ); threadLabel.setText(threadInfo); // Change color if deadlocks detected if (deadlockCount > 0) { threadLabel.setForeground(Color.RED); } else { threadLabel.setForeground(Color.BLACK); } } catch (Exception e) { threadLabel.setText("Error"); } } private void updateOSInfo() { try { OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); String osName = osBean.getName(); String arch = osBean.getArchitecture(); double loadAverage = osBean.getSystemLoadAverage(); String osInfo = String.format( "<html><center>%s<br>%s<br>Load: %s</center></html>", osName, arch, loadAverage >= 0 ? df.format(loadAverage) : "N/A" ); osLabel.setText(osInfo); } catch (Exception e) { osLabel.setText("Error"); } } private void updateProcessList() { try { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); StringBuilder processText = new StringBuilder(); // Get top threads by CPU time ThreadInfo[] threadInfos = threadBean.dumpAllThreads(false, false); Arrays.sort(threadInfos, (t1, t2) -> Long.compare(threadBean.getThreadCpuTime(t2.getThreadId()), threadBean.getThreadCpuTime(t1.getThreadId()))); processText.append(String.format("%-8s %-20s %-12s %s\n", "ID", "Name", "State", "CPU Time")); processText.append("──────────────────────────────────────────────────\n"); int count = 0; for (ThreadInfo info : threadInfos) { if (count++ >= 15) break; // Show top 15 long cpuTime = threadBean.getThreadCpuTime(info.getThreadId()); String cpuTimeStr = cpuTime >= 0 ? formatNanos(cpuTime) : "N/A"; processText.append(String.format("%-8d %-20s %-12s %s\n", info.getThreadId(), truncateString(info.getThreadName(), 20), info.getThreadState(), cpuTimeStr )); } processListArea.setText(processText.toString()); } catch (Exception e) { processListArea.setText("Error retrieving process information"); } } private void updateCharts() { // Data is already updated in the history lists // The chart panel will use these lists when painting } private void exportReport() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Export System Report"); if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { try { java.io.File file = fileChooser.getSelectedFile(); PrintWriter writer = new PrintWriter(file); writer.println("System Monitoring Report"); writer.println("Generated: " + new Date()); writer.println("================================="); writer.println(); // Write system information writer.println("CPU Usage: " + cpuLabel.getText()); writer.println("Memory Usage: " + memoryLabel.getText()); writer.println("Heap Usage: " + heapLabel.getText()); writer.println("Thread Info: " + threadLabel.getText().replaceAll("<[^>]*>", "")); writer.close(); JOptionPane.showMessageDialog(this, "Report exported successfully!"); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error exporting report: " + e.getMessage(), "Export Error", JOptionPane.ERROR_MESSAGE); } } } private void showSettings() { JDialog settingsDialog = new JDialog(this, "Monitor Settings", true); settingsDialog.setLayout(new GridLayout(0, 2, 10, 10)); settingsDialog.setSize(300, 200); settingsDialog.setLocationRelativeTo(this); settingsDialog.add(new JLabel("Refresh Interval (ms):")); JTextField intervalField = new JTextField(String.valueOf(UPDATE_INTERVAL)); settingsDialog.add(intervalField); settingsDialog.add(new JLabel("Max History Points:")); JTextField historyField = new JTextField("50"); settingsDialog.add(historyField); JButton saveButton = new JButton("Save"); saveButton.addActionListener(e -> { // In a real implementation, save these settings settingsDialog.dispose(); }); settingsDialog.add(saveButton); settingsDialog.setVisible(true); } private String formatNanos(long nanos) { if (nanos < 1000) return nanos + " ns"; if (nanos < 1000000) return (nanos / 1000) + " μs"; if (nanos < 1000000000) return (nanos / 1000000) + " ms"; return (nanos / 1000000000) + " s"; } private String truncateString(String str, int maxLength) { if (str.length() <= maxLength) return str; return str.substring(0, maxLength - 3) + "..."; } // Custom panel for drawing charts private class ChartPanel extends JPanel { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int width = getWidth(); int height = getHeight(); int padding = 20; // Draw CPU history chart drawLineChart(g2d, cpuHistory, "CPU Usage %", Color.RED, width / 2 - padding, height, padding); // Draw Memory history chart drawLineChart(g2d, memoryHistory, "Memory Usage %", Color.BLUE, width / 2, height, padding); } private void drawLineChart(Graphics2D g2d, java.util.List<Double> data, String title, Color color, int xOffset, int height, int padding) { if (data.isEmpty()) return; int chartWidth = getWidth() / 2 - padding * 2; int chartHeight = height - padding * 3; // Draw title g2d.setColor(Color.BLACK); g2d.drawString(title, xOffset + padding, padding); // Draw axes g2d.drawRect(xOffset + padding, padding * 2, chartWidth, chartHeight); // Draw data points g2d.setColor(color); for (int i = 1; i < data.size(); i++) { int x1 = xOffset + padding + (i - 1) * chartWidth / Math.max(1, data.size() - 1); int y1 = padding * 2 + chartHeight - (int)(data.get(i - 1) * chartHeight / 100); int x2 = xOffset + padding + i * chartWidth / Math.max(1, data.size() - 1); int y2 = padding * 2 + chartHeight - (int)(data.get(i) * chartHeight / 100); g2d.drawLine(x1, y1, x2, y2); } } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel()); } catch (Exception e) { e.printStackTrace(); } new SystemMonitorGUI().setVisible(true); }); } }

Advanced Monitoring Features

Network Monitoring Component

import java.net.*; import java.util.*; public class NetworkMonitor { private Map<String, NetworkInterfaceStats> interfaceStats = new HashMap<>(); public void monitorNetwork() { try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface ni = interfaces.nextElement(); if (ni.isUp() && !ni.isLoopback()) { NetworkInterfaceStats stats = getInterfaceStats(ni); interfaceStats.put(ni.getName(), stats); } } } catch (SocketException e) { System.err.println("Error monitoring network: " + e.getMessage()); } } private NetworkInterfaceStats getInterfaceStats(NetworkInterface ni) { NetworkInterfaceStats stats = new NetworkInterfaceStats(); stats.setInterfaceName(ni.getDisplayName()); try { List<InterfaceAddress> addresses = ni.getInterfaceAddresses(); for (InterfaceAddress addr : addresses) { InetAddress inetAddr = addr.getAddress(); if (inetAddr instanceof Inet4Address) { stats.setIpv4Address(inetAddr.getHostAddress()); } } // Get basic statistics (this would need more sophisticated monitoring) stats.setBytesReceived(0); // Would need to track over time stats.setBytesSent(0); stats.setPacketsReceived(0); stats.setPacketsSent(0); } catch (Exception e) { // Handle exception } return stats; } public Map<String, NetworkInterfaceStats> getInterfaceStats() { return interfaceStats; } public static class NetworkInterfaceStats { private String interfaceName; private String ipv4Address; private long bytesReceived; private long bytesSent; private long packetsReceived; private long packetsSent; // Getters and setters public String getInterfaceName() { return interfaceName; } public void setInterfaceName(String interfaceName) { this.interfaceName = interfaceName; } public String getIpv4Address() { return ipv4Address; } public void setIpv4Address(String ipv4Address) { this.ipv4Address = ipv4Address; } public long getBytesReceived() { return bytesReceived; } public void setBytesReceived(long bytesReceived) { this.bytesReceived = bytesReceived; } public long getBytesSent() { return bytesSent; } public void setBytesSent(long bytesSent) { this.bytesSent = bytesSent; } public long getPacketsReceived() { return packetsReceived; } public void setPacketsReceived(long packetsReceived) { this.packetsReceived = packetsReceived; } public long getPacketsSent() { return packetsSent; } public void setPacketsSent(long packetsSent) { this.packetsSent = packetsSent; } } }

Alert System

import java.util.*; import java.util.concurrent.*; public class AlertSystem { private List<Alert> activeAlerts = new CopyOnWriteArrayList<>(); private Map<String, Double> thresholds = new HashMap<>(); private AlertListener alertListener; public AlertSystem() { // Set default thresholds thresholds.put("cpu.usage", 90.0); thresholds.put("memory.usage", 85.0); thresholds.put("heap.usage", 90.0); thresholds.put("thread.count", 500.0); thresholds.put("disk.usage", 90.0); } public void checkMetrics(SystemMetrics metrics) { checkCPUUsage(metrics.getCpuUsage()); checkMemoryUsage(metrics.getMemoryUsage()); checkHeapUsage(metrics.getHeapUsage()); checkThreadCount(metrics.getThreadCount()); } private void checkCPUUsage(double usage) { if (usage > thresholds.get("cpu.usage")) { triggerAlert("HIGH_CPU", String.format("CPU usage is high: %.2f%%", usage), Alert.Severity.WARNING); } } private void checkMemoryUsage(double usage) { if (usage > thresholds.get("memory.usage")) { triggerAlert("HIGH_MEMORY", String.format("Memory usage is high: %.2f%%", usage), Alert.Severity.WARNING); } } private void checkHeapUsage(double usage) { if (usage > thresholds.get("heap.usage")) { triggerAlert("HIGH_HEAP", String.format("Heap memory usage is high: %.2f%%", usage), Alert.Severity.ERROR); } } private void checkThreadCount(int count) { if (count > thresholds.get("thread.count")) { triggerAlert("HIGH_THREADS", String.format("High thread count: %d", count), Alert.Severity.WARNING); } } private void triggerAlert(String type, String message, Alert.Severity severity) { Alert alert = new Alert(type, message, severity, new Date()); // Check if similar alert already exists if (!activeAlerts.contains(alert)) { activeAlerts.add(alert); if (alertListener != null) { alertListener.onAlertTriggered(alert); } } } public void clearAlert(String type) { activeAlerts.removeIf(alert -> alert.getType().equals(type)); } public List<Alert> getActiveAlerts() { return new ArrayList<>(activeAlerts); } public void setAlertListener(AlertListener listener) { this.alertListener = listener; } public static class Alert { public enum Severity { INFO, WARNING, ERROR, CRITICAL } private String type; private String message; private Severity severity; private Date timestamp; public Alert(String type, String message, Severity severity, Date timestamp) { this.type = type; this.message = message; this.severity = severity; this.timestamp = timestamp; } // Getters public String getType() { return type; } public String getMessage() { return message; } public Severity getSeverity() { return severity; } public Date getTimestamp() { return timestamp; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Alert alert = (Alert) obj; return type.equals(alert.type); } @Override public int hashCode() { return type.hashCode(); } } public interface AlertListener { void onAlertTriggered(Alert alert); } } class SystemMetrics { private double cpuUsage; private double memoryUsage; private double heapUsage; private int threadCount; // Getters and setters public double getCpuUsage() { return cpuUsage; } public void setCpuUsage(double cpuUsage) { this.cpuUsage = cpuUsage; } public double getMemoryUsage() { return memoryUsage; } public void setMemoryUsage(double memoryUsage) { this.memoryUsage = memoryUsage; } public double getHeapUsage() { return heapUsage; } public void setHeapUsage(double heapUsage) { this.heapUsage = heapUsage; } public int getThreadCount() { return threadCount; } public void setThreadCount(int threadCount) { this.threadCount = threadCount; } }

Running the System Monitor

How to Run:

  1. Console Version:
 javac SystemMonitor.java java SystemMonitor
  1. GUI Version:
 javac SystemMonitorGUI.java java SystemMonitorGUI

Features Included:

  • Real-time CPU monitoring with usage percentage and history
  • Memory monitoring including physical and heap memory
  • Thread information with deadlock detection
  • Process listing showing top CPU-consuming threads
  • Disk usage monitoring for all drives
  • Network interface information
  • Alert system for threshold breaches
  • Historical charts for performance trends
  • Export functionality for reports
  • Configurable refresh rates

This system monitoring dashboard provides comprehensive insights into Java application and system performance, making it useful for development, testing, and production monitoring scenarios.

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper