Java Series: Basics Q&A Part 7

End of Basic Q&A Series!

Q31. How to defend Java Application from Inject Attack?

Inject is a common attack method and it gives attacker a way to inject intrust dynamic content into your code and get executed. The most common inject attack is SQL attack, for example if we plan to run the following SQL:

Select * from use_info where username = “input_usr_name” and password = “input_pwd”
“ or ""="
Select * from use_info where username = “input_usr_name” and password = “” or “” = “”
ll input_file_name
input_file_name;rm -rf /*

Q32. How to write secure Java code?

Avoid low cost DoS attack via program flaws, like:

  • Hash collision attack. Especially pay attention to computational heavy tasks, like encryption/decryption/image processing etc.
  • Services that take user input, like unzip files (Zip Bomb)
  • DB connection, file descriptor leak or even reentrant lock. Make sure all resources can be released under all scenarios.
if (a + b < c) { // … }
try {
// ..
} catch (Exception e) {
throw new RuntimeException(hostname + port + “ doesn’t response”);

Q33. How to diagnose backend services slowing down?

A couple directions:

  1. Monitor JVM. Any Full GC or Minor GC is getting longer?
  2. Profiling.
  3. Check CPU usage.
  4. Use vmstat to check the number of context switches.

Q34. Does Lambda always slow down Java program?

Not really. Theoretically speaking, Lambda has the same performance as imperative programming. If you see Benchmarks saying that, you need to firstly make sure the benchmark is a fair one. For example the code executed in two different cases have different cost except for syntax difference, like auto-boxing /unboxing.

public void testMethod() {
// Put your benchmark code here.
  1. Avoid JVM dead code elimination.
  2. Avoid constant folding.
  3. Avoid false sharing.

Q35. How does JVM optimize Java code?

JVM optimizes code in both runtime and JIT. Runtime optimization includes biased lock, TLAB, etc. JIT optimization compiles hot code into native code including inline functions, escape analysis etc.

-XX:UnlockDiagnosticVMOptions -XX:+LogCompilation -XX:LogFile=<your_file_path>

Q36. MySQL isolation level & Optimistic/Pessimistic Lock?

Isolation Level define how to ensure correctness of database write/read operation in a concurrent environment.

  1. Read committed. User is able to see committed changes, no intermittent changes. This doesn’t guarantee second read would get the same data, Phantom Read might happen.
  2. Repeatable reads. The same data will be consistent during multiple reads, this is the default level of isolation in MySQL.
  3. Serializable. This is the highest level of isolation. There will be a shared lock for reading and update needs exclusive lock.

hacker, lifetime learner