Java and JVM Q&A: Performance, Tools, and Best Practices

This article compiles a Java club’s Q&A covering backend development essentials—from network bandwidth checks and static‑method hooking to JNI choices, OSGi modularity, plugin performance, CPU‑heavy thread analysis, ConcurrentHashMap improvements, micro‑service frameworks, cross‑data-center protocols, JVM GC mechanisms, inheritance alternatives, ThreadLocal pitfalls, career advice, cloning, generics erasure, JVM tuning, multithreading strategies, lock upgrades, monitoring tools, database failure handling, Spring Data JPA design, and distributed transaction practices.

Meituan Technology Team
Meituan Technology Team
Meituan Technology Team
Java and JVM Q&A: Performance, Tools, and Best Practices

This document is a collection of Q&A from a Java club, covering a wide range of backend development topics such as network bandwidth monitoring, hooking static methods, JNI usage, OSGi modularity, plugin performance evaluation, CPU analysis, ConcurrentHashMap improvements, micro‑service frameworks, cross‑data‑center protocols, JVM garbage‑collection mechanisms, multiple inheritance alternatives, ThreadLocal pitfalls, career development for Java engineers, object cloning, JVM tuning, generics type erasure, advanced JVM study resources, multithreading strategies, biased‑lock upgrades, monitoring tools, database failure handling, Spring Data JPA design, and distributed transaction practices.

Network bandwidth check : Tools like iftop, dstat, and sar can be used. A 1 Gbps NIC is saturated when traffic reaches roughly 10 MB/s (80 Mbps).

Hooking static methods : Use btrace and related utilities.

JNI perspective : Modern software development favors using the most suitable tool for each task rather than a single language.

OSGi adoption : Not recommended for most production systems due to high cost versus benefit, but valuable for learning Java 9 modularity and class‑loader internals.

Plugin performance assessment : Measure method execution time, memory footprint, and GC impact.

CPU‑heavy JVM thread analysis script :

#!/bin/sh
 ts=$(date +"%s")
 jvmPid=$1
 defaultLines=100
 defaultTop=20
 threadStackLines=${2:-$defaultLines}
 topThreads=${3:-$defaultTop}
 jvmCapture=$(top -b -n1 | grep java )
 threadsTopCapture=$(top -b -n1 -H | grep java )
 jstackOutput=$(echo "$(jstack $jvmPid )" )
 topOutput=$(echo "$(echo "$threadsTopCapture" | head -n $topThreads | perl -pe 's/\e\[?.*?[\@-~] ?//g' | awk '{gsub(/^ +/,"");print}' | awk '{gsub(/ +|[+-]/," ");print}' | cut -d " " -f 1,9 )
 ")
 echo "*************************************************************************************************************"
 uptime
 echo "Analyzing top $topThreads threads"
 echo "*************************************************************************************************************"
 printf %s "$topOutput" | while IFS= read line; do
   pid=$(echo $line | cut -d " " -f 1)
   hexapid=$(printf "%x" $pid)
   cpu=$(echo $line | cut -d " " -f 2)
   echo -n $cpu"% [$pid] "
   echo "$jstackOutput" | grep "tid.*0x$hexapid " -A $threadStackLines | sed -n -e '/0x'$hexapid'/,/tid/ p' | head -n -1
   echo "
"
 done
 echo "
"

This script prints all JVM threads sorted by CPU usage and shows their stack traces.

ConcurrentHashMap in Java 8 : Introduced finer‑grained locking, bucket‑level synchronized, and a red‑black tree conversion for buckets with >8 entries and capacity >64, reducing lookup complexity from O(N) to O(log N). Segment locks were removed; only put, resize, and expansion acquire locks.

Dubbo vs Spring Cloud : They operate at different layers; Spring Cloud is a broader micro‑service solution, while Dubbo is an RPC framework.

Cross‑data‑center communication : Use high‑quality dedicated links or batch data transfer to mitigate latency.

JVM generational GC : Old‑to‑young references are tracked via a card table, avoiding full old‑generation scans.

Multiple inheritance in Java : Java avoids it by allowing multiple interface implementation and using composition; languages like Python use mixins.

Career advice for Java engineers : Write example projects on GitHub, read open‑source code, and follow technical articles.

Clone method : Override public clone() to provide deep copy semantics; the default protected Object.clone() performs shallow copy.

JVM tuning for young/old generation sizes : Choose larger young generation for latency‑sensitive apps, larger old generation for throughput‑oriented workloads; monitor GC logs to balance pause times.

Generics type erasure : Workarounds include using languages without erasure (C#, Kotlin) or careful reflection; example code:

public static void main(String[] args) {
    List<Integer> intList = new ArrayList<>();
    intList.add(1);
    try {
        Method method = intList.getClass().getDeclaredMethod("add", Object.class);
        try {
            method.invoke(intList, "string1");
            method.invoke(intList, 0.5f);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
    for (Object i : intList) {
        System.out.println(i.toString());
    }
}

Advanced JVM study path : After "Deep Understanding of the JVM" read the official JVM specification, Oracle white‑papers, GC algorithm books, then explore HotSpot source and Alibaba's "JVM Secrets".

Multithreading best practices : For short‑lived high‑concurrency tasks, set thread pool size to CPU cores + 1. For I/O‑bound workloads, increase pool size; for CPU‑bound, keep it modest. Consider architectural changes for long‑running high‑concurrency jobs.

Biased‑lock to lightweight‑lock upgrade (excerpt from biasedLock.cpp in OpenJDK 1.8):

if (highest_lock != NULL) {
    // Fix up highest lock to contain displaced header and point
    // object at it
    highest_lock->set_displaced_header(unbiased_prototype);
    // Reset object header to point to displaced mark
    obj->set_mark(markOopDesc::encode(highest_lock));
    assert(!obj->mark()->has_bias_pattern(), "illegal mark state: stack lock used bias bit");
    if (TraceBiasedLocking && (Verbose || !is_bulk)) {
      tty->print_cr("  Revoked bias of currently-locked object");
    }
  }

Visual monitoring tools include JProfiler, JConsole, Java VisualVM, and command‑line utilities jps, jstack, jmap, jhat, jstat.

Database update failure handling : Use compensation transactions and retries.

Spring Data JPA design : Consider the Active Record pattern; decide between direct entity serialization or DTOs based on coupling and data redundancy needs.

Meituan distributed transaction practice : Mentioned but details omitted.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaJVMperformanceconcurrencyProfilingtools
Meituan Technology Team
Written by

Meituan Technology Team

Over 10,000 engineers powering China’s leading lifestyle services e‑commerce platform. Supporting hundreds of millions of consumers, millions of merchants across 2,000+ industries. This is the public channel for the tech teams behind Meituan, Dianping, Meituan Waimai, Meituan Select, and related services.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.