October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories

October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Elapsed Time for Shell Scripts

lot of times you want to calculate the time it takes for a part of a shell script to run. Here is one of the ways you can do this:

T1=$(date +%s)
# Do something here
T2=$(date +%s)
diffsec="$(expr $T2 - $T1)"
echo | awk -v D=$diffsec '{printf "Elapsed time: %02d:%02d:%02d\n",D/(60*60),D%(60*60)/60,D%60}'

This will tell you the elapsed time between setting T1 and setting T2. The output is formatted as HH:MM:SS and printed to the console. You can easily redirect to a file for logging.

 

#!/bin/bash

# Create function for calculating time difference.
function time_diff()
{
seconds=$(( $2 – $1 ))
hours=$((seconds / 3600))
seconds=$((seconds % 3600))
minutes=$((seconds / 60))
seconds=$((seconds % 60))
EX_TIME=`printf “%02d:%02d:%02d” $hours $minutes $seconds`

}

# Store the time before job start.
TIME1=`date +%s`

# Execute your command here. Taking sleep 10 as job right now.
sleep 10

# Store the time after finishing job.
TIME2=`date +%s`

# Pass the both the time to function
time_diff $TIME1 $TIME2

# EX_TIME will store the execution time of process.
echo “Execution time is $EX_TIME”

Simple BASH script example for showing the elapsed time for a script to execute:

#!/bin/bash

start_time=`date +%s`

end_time=`date +%s` time_elapsed=$(($end_time-$start_time))

echo “Script execution took $time_elapsed seconds.”

#!/bin/bash
NOW=$(date +"%d.%m.%Y")
FILE=/tmp/$NOW.log
df -ahl | grep -i sda1 > "$FILE"

 

Seeing “2 seconds” is fine, but I’m interested in it being “2.255322 seconds.” A better solution:
#!/bin/sh
START=`date +%s%N`

# Do stuff here

END=`date +%s%N`
ELAPSED=`echo “scale=8; ($END – $START) / 1000000000” | bc`

 

Shell Script to send email alerts when the server load average is more than 5

 

#!/bin/bash
avg=`uptime | awk ‘{print $8? ” $9 ” “$10 $11 $12 }’ | tr -s , ” “`
cur=`uptime | awk ‘{print $10}’ | tr -d , | cut -d. -f1`
str=”=============================”
info=”Curent $avg”

if [ $cur -ge 5 ]; then
info1=”Server load is high presently”
echo -e “$str\n$info\n$info1\n$str” | mail -s “Alert: Load Average for `hostname` on `date`” abc@yourdom.com
else
# echo -e “$str\n$info\n$str”
fi

 

 

1. Shell Script : Find All Zip / Rar Files Then Unzip / Unrar

Shell Script

Server1:~$ cat rar.sh

#!/bin/bash #this line must be in every bash script, just ensure that you use correct path

list=`find /home/yevhen/ -type f -name “*.rar”` # get list of file and write this list to variable with name list, find command used to find all files (-type f) where name match *.rar (-name key)

for line in $list; do # this line take every line from list to line variable

DEST=${line%/*} # remove from line filename, so just destination will be in DEST variable.

unrar x $line $DEST # unrar file from line variable to DEST dir

done # finish of for loop.

Output

    Server1:~$ ./rar.sh

UNRAR 3.93 freeware Copyright (c) 1993-2010 Alexander Roshal

Extracting from /home/yevhen/Dropbox/Yevhen/test.rar

Extracting /home/yevhen/Dropbox/Yevhen/wget.sh OK
All OK

UNRAR 3.93 freeware Copyright (c) 1993-2010 Alexander Roshal

Extracting from /home/yevhen/Pictures/test.rar

Extracting /home/yevhen/Pictures/wget.sh OK
All OK

===============================================30000
2. Shell Script To Check Disk Usage Is Out Of Space

Shell Script

#!/bin/bash

threshold=”20? # This set threshold value

i=2 #Counter, will be used later, set to 2, since first line in df output is description.

result=`df -kh |grep -v “Filesystem” | awk ‘{ print $5 }’ | sed ‘s/%//g’` # Getting list of percentage of all disks, df -kh show all disk usage, grep -v – without description line, awk ‘{ print $5 }’ – we need only 5th value from line and sed ‘s/%//g’ – to remove % from result.

for percent in $result; do # for every value in result we start loop.

if ((percent > threshold)) # compare, if current value bigger than threshold, if yes next lines.
then

partition=`df -kh | head -$i | tail -1| awk ‘{print $1}’` # taking name of partition, here we use counter. Df list of all partitions, head – take only $i lines from top, tail -1 take only last line, awk ‘{print $1}’ – take only first value in line.

echo “$partition at $(hostname -f) is ${percent}% full” #print to console – what partition and how much used in %.

fi # end of if loop

let i=$i+1 # counter increased by 1.

done # end of for loop.
Shell Script Result

Server:~/$ df -kh
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 52G 4.7G 45G 10% /
tmpfs 1.9G 0 1.9G 0% /lib/init/rw
udev 1.9G 192K 1.9G 1% /dev
tmpfs 1.9G 2.6M 1.9G 1% /dev/shm
/dev/sda6 92G 22G 66G 25% /home

Server:~/$ ./df_script.sh
/dev/sda6 at yevhen.lviv.example.com is 25% full

==========================================
3. Shell Script : Check Ping To Remote Host And Port Opened

Shell Script

Test Ping And Open Port

#!/bin/bash

# check if service name passed to script as argument, if there no arguments (0) do next

if [ “$#” = “0” ];

then

#write to terminal usage

echo “Usage: $0 ”

#since no arguments – we need to exit script and user re-run

exit 1
fi

#writing parameters to variables

host=$1
port=$2
email=”test@expertslogin.com”
subject=”Script result”

#Check if ping ok -q to quite mod, -c 4 for 4 checks

if ping -q -c 4 $host >/dev/null
then
# next lines writes result variable

ping_result=”OK”
else
ping_result=”NOT OK”

fi #end of fi loop

#next command check if port opened via nc command, and getting exit status of nc command

nc_result=`nc -z $host $port; echo $?`

#check of exit status of nc command, and write results to variables

if [ $nc_result != 0 ];
then
port_result=”not opened”
else
port_result=”opened”
fi #exit of fi loop

#writing message that script will email and write to output

message=”Ping to host – ${ping_result}, port $port ${port_result}.”

#next check if ping or port check is failed (ping if not OK and exit status of nc if not 0)

if [ “$ping_result” != “OK” -o “$nc_result” != “0” ];
then
echo “$message” #this line write warning message to terminal

echo “$message” | mail -s “$subject” $email #this line send email

fi

< h3=””>

Ping to localhost and check is 22 port opened (ssh server)

desktop:~/$ ./script 127.0.0.1 22
Ping to host – OK, port 22 not opened.
desktop:~/$

<>

===================================================

4. Shell Script : Service Status Check And start If It’s Not Running

Shell Script

#!/bin/bash

if [ “$#” = 0 ] # check if service name passed to script as argument, if there no arguments (0) do next

then
echo “Usage $0 ” #write to terminal usage

exit 1 #since no arguments – we need to exit script and user re-run it

fi

service=$1 #get service name from first argument

is_running=`ps aux | grep -v grep| grep -v “$0? | grep $service| wc -l | awk ‘{print $1}’` #this check
#if service running using ps command, after we remove our process from output, since script will also
# match, with wc we count number of matching lines .

if [ $is_running != “0” ] ; # is number of lines are not 0 do next

then

echo “Service $service is running” #just put this line to terminal

else #if number of precesses is 0

echo “Service $service is not running” #just put this string to terminal

initd=`ls /etc/init.d/ | grep $service | wc -l | awk ‘{ print $1 }’` #checking for files in /etc/init.d
#(directory with start-up scripts) with name similar to service

if [ $initd = “1” ]; #if there is script with similar name

then
startup=`ls /etc/init.d/ | grep $service` # this line get name of startup script (ls –
# lists files in directory

echo -n “Found startap script /etc/init.d/${startup}. Start it? Y/n ? ” #just put to
#terminal this line

read answer #waiting for user answer

if [ $answer = “y” -o $answer = “Y” ]; #if answer Y or y

then
echo “Starting service…”

/etc/init.d/${startup} start # running startup script

fi #exit of if loop

fi #exit of if loop

fi#exit of if loop

Results

server:~/$ ./service.sh apparmor
Service apparmor is not running
Found startap script /etc/init.d/apparmor. Start it? Y/n ? Y
Starting service…
* Starting AppArmor profiles [OK]

GNU tar (Tape ARchive)

GNU tar (Tape ARchive) saves multiple files together into a single tape or disk archive, and can restore individual files from the archive. Here are some Linux tar Command with Useful Practical Examples

Some useful command line switches are given below, which are used in this article.

c => create an archive file.
v => show the detailed output ( or porgress ) of command.
x => extract an archive file.
f => filename of archive file.
z => Use archive through gzip.
t => viewing content of archive file.
j => Use archive through bzip2.
C => Use of define destination directory.
W => Verify a archive file.
Example 1: Create a .tar Archive File.

Below command will create an compressed ( tar ) file using all files and directories ( with subdirectories ) of /var/log directory.

# tar cvf rmohan-16-apr-2013.tar /var/log
Example 2: Create a .tar.gz Archive File.

Below command will create an gzip compressed ( tar.gz ) file using all files and directories ( with subdirectories ) of /var/log directory. I will create more compressed file than .tar file.

# tar czvf rmohan-16-apr-2013.tar.gz /var/log
Example 3: Create a .tar.bz2 Archive File.

This example is used for creating bz2 files. bz2 files are higher compressed than .tar and .tar.gz files. Its also take more time to compress than others.

# tar cjvf rmohan-16-apr-2013.tar.bz2 /var/log
Check difference between .tar , .tar.gz and .tar.bz2 file sizes.

# ls -l rmohan-16-apr-2013.tar*
-rw-r–r–. 1 root root 26818560 Apr 12 22:25 rmohan-16-apr-2013.tar
-rw-r–r–. 1 root root 697802 Apr 13 00:25 rmohan-16-apr-2013.tar.bz2
-rw-r–r–. 1 root root 1091399 Apr 13 00:26 rmohan-16-apr-2013.tar.gz
As per above output .tar.bz2 is higher compressed and .tar is lower compressed file.

Example 4: List content of .tar, .tar.gz, .tar.bz2 Archive File.

Some times we requried to list content of archive file without extracting them. Below example will help you to do it.

# tar -tvf rmohan-16-apr-2013.tar
# tar -tvf rmohan-16-apr-2013.tar.gz
# tar -tvf rmohan-16-apr-2013.tar.bz2
Example 5: Uncompress .tar Archive File.

To uncompress a .tar file use below command. It will extract all files and directories ( with subdirectories ) in current path. To uncompress in different location check Example 8.

# tar -xvf rmohan-16-apr-2013.tar
Example 6: Uncompress .tar.gz Archive File.

To uncompress a .tar.gz ( tar + gzip ) file use below command. It will extract all files and directories in current path.

# tar -xvf rmohan-16-apr-2013.tar
Example 7: Uncompress .tar.bz2 Archive File.

Use below example to uncompress a .tar.bz2 ( tar + bz2 ) file. It will extract all files and directories in current path.

# tar -xvf rmohan-16-apr-2013.tar
Example 8: Extract Archive in different location.

Use C command line switch to specify a location for extracting an archive file.

# tar xf rmohan-16-apr-2013.tar -C /Output/Dir/
Example 9: Verify .tar Archive Files.

To verify .tar file use ‘W’ switch with ‘t’. For you information .tar.gz and .tar.bz2 can not be verified using this. Use below command to verify your tar file.

# tar tvWf /root/rmohan-16-apr-2013.tar
Sample Output:

tar: This does not look like a tar archive
tar: Skipping to next header
tar: VERIFY FAILURE: 13 invalid headers detected
Verify -rw——- root/root 0 2013-03-31 03:50 var/log/spooler-20130407
Verify -rw——- root/utmp 384 2013-04-12 21:31 var/log/btmp
Verify -rw-r–r– root/root 211614 2013-03-18 19:20 var/log/dracut.log
Verify -rw——- root/root 5793 2013-04-12 22:20 var/log/secure
Verify -rw-r–r– root/root 4952 2013-04-01 14:40 var/log/krb5kdc.log-20130401
Verify drwxr-xr-x root/root 0 2011-12-08 06:00 var/log/spice-vdagentd/
Verify drwx—— root/root 0 2013-04-12 14:57 var/log/samba/
Verify -rw-r–r– root/root 0 2013-04-09 01:58 var/log/samba/log.192.168.1.199
Verify -rw-r–r– root/root 1972 2013-04-12 14:37 var/log/samba/log.nmbd
var/log/samba/log.nmbd: Mod time differs
var/log/samba/log.nmbd: Size differs
Verify -rw——- root/utmp 384 2013-03-18 20:26 var/log/btmp-20130401
Verify -rw-r–r– root/root 1382 2013-04-11 13:53 var/log/kadmind.log
Verify drwxrwx–T root/gdm 0 2013-04-11 13:53 var/log/gdm/
Verify -rw-r–r– root/root 0 2013-04-11 13:53 var/log/gdm/:0-slave.log
Verify -rw-r–r– gdm/gdm 1387 2013-04-05 17:07 var/log/gdm/:0-greeter.log.1
Verify -rw-r–r– root/root 18983 2013-03-25 14:10 var/log/gdm/:0.log.3
Verify -rw-r–r– root/root 19028 2013-04-05 17:06 var/log/gdm/:0.log.1
Verify -rw-r–r– root/root 18983 2013-03-22 15:42 var/log/gdm/:0.log.4
Verify -rw-r–r– root/root 98 2013-04-05 17:07 var/log/gdm/:0-slave.log.1
Verify -rw-r–r– root/root 18983 2013-04-11 13:53 var/log/gdm/:0.log
tar: Exiting with failure status due to previous errors
Due to long list of output, some of output has been hidden in above command output.

 

GPG file encryption command line in Linux

GPG file encryption using key pair
GPG basic file encryption doesn’t required public/private key. But to make a encrypted file more secure you can use RSA/DSA algorithms. These algorithms generates public and private keys to encrypt file.

There are three criteria to use GPG file encryption.

1. Encrypt/Decrypt file locally for same user account.
2. Encrypt file for other user.
3. Decrypt other users file.

The very first step is to generate key pair using below command.

# gpg –gen-key
Output:

gpg (GnuPG) 1.4.5; Copyright (C) 2006 Free Software Foundation, Inc.
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions. See the file COPYING for details.

Please select what kind of key you want:
(1) DSA and Elgamal (default)
(2) DSA (sign only)
(5) RSA (sign only)
Your selection?
DSA keypair will have 1024 bits.
ELG-E keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048)
Requested keysize is 2048 bits
Please specify how long the key should be valid.
0 = key does not expire
= key expires in n days
w = key expires in n weeks
m = key expires in n months
y = key expires in n years
Key is valid for? (0)
Key does not expire at all
Is this correct? (y/N) y

You need a user ID to identify your key; the software constructs the user ID
from the Real Name, Comment and Email Address in this form:
“Heinrich Heine (Der Dichter) ”

Real name: Mohan Ramadoss
Email address: rmohan@rmohan.com
Comment: System Admin
You selected this USER-ID:
“Mohan Ramadoss (System Admin) ”

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? o
You need a Passphrase to protect your secret key.

We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
++++++++++++++++++++..+++++++++++++++.++++++++++++++++++++.+++++.+++++.+++++++++++++++++++++++++.+++++.++++++++++++++++++++++++++++++…+++++>+++++..+++++>+++++……………………………………………………..+++++

Not enough random bytes available. Please do some other work to give
the OS a chance to collect more entropy! (Need 284 more bytes)

We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
+++++..+++++.++++++++++..++++++++++.++++++++++..++++++++++..+++++++++++++++.+++++..+++++.++++++++++.+++++.++++++++++.++++++++++..++++++++++++++++++++++++++++++..+++++>++++++++++.>+++++>+++++.<+++++………………………………………………………………………………………….>+++++…………………+++++^^^
gpg: /root/.gnupg/trustdb.gpg: trustdb created
gpg: key 2AE39E50 marked as ultimately trusted
public and secret key created and signed.

gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0 valid: 1 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 1u
pub 1024D/2AE39E50 2013-03-14
Key fingerprint = 0D89 4697 E22A A6CC 3017 5EA1 0389 ED6D 2AE3 9E50
uid Mohan Ramadoss (System Admin)
sub 2048g/9102AC9C 2013-03-14
1. Encrypt/Decrypt file locally for same user account.

Encrypt file for single user only. No one other can decrypt this file.

# gpg –encrypt –recipient ‘Mohan Ramadoss’ rmohan.txt
–recipient name should be same as used in key generation. Above command will automatically generate a encrypted file named rmohan.txt.gpg

Decrypt your own file rmohan.txt.gpg

# gpg –output rmohan2.txt –decrypt rmohan.txt.gpg
–output or -o is used to specify output filename. Above command will prompt for passphrase used in key pair.

2. Encrypt file for other user.

Use #1 steps to generate encrypted file. Finally share your public key and encrypted file ( rmohan.txt.gpg ) with other users. To export your public key use following command.

# gpg –armor –output pubkey.txt –export ‘Mohan Ramadoss’

Check your public key. It should be like below

# cat pubkey.txt
—–BEGIN PGP PUBLIC KEY BLOCK—–
Version: GnuPG v1.4.5 (GNU/Linux)

mQGiBFFBPwsRBADWAxKxCxLsZ1ZJ512auBkEw51HlF5+k18Yp1giOqIYtbRUPVeq
Y5o5knVKjlJDlVA0/rGh18fbKgubjZl1PL1R+tT0bMIDIs5+hg+S60nSlxBGOhYz
8h+nuY4GbOMdG0V4DJwgpOg7Haywljs0epYPtcdroRIrLg8owjcpYtIm1wCgl75F
XP6XU/CPJJoZp7DrC2Ukrg8EALra/Rwk5MXi3G8rT3dq1rX0wMmFPh+A1osnYIlM
RaaNGi28MdTGv/61pMz6ItPgBTglp6hzkRyixIuBXxqkwP8489o2MwzzwVbAUjUb
i8/U4Y3eW1jii8WBZydUn+MaMx4sKSnYXjoIHvRsiDhnIWvVUdbaeet0wOdlLj/X
+xl/BACl0xykv21zpMUXnKIadM2DeD6esMHtijzJYBfg6tgQmwjbFMtLsiPk0GdG
RCYQ0vTiSn0m78dcqsQjvfTSzd0kFnOvSkC3kNf/+cqY9ZHnin4J55LfI1m0yHhB
Ybm2zutx9f6+RB7Ariuhok9BXPVd5cPf5lO6DxmIF2qAjk83nLQ8UmFodWwgS3Vt
YXIgKExpbnV4IFN5c3RlbSBBZG1pbikgPHJhaHVsLmt1bWFyMTA5OUBnbWFpbC5j
b20+iGAEExECACAFAlFBPwsCGwMGCwkIBwMCBBUCCAMEFgIDAQIeAQIXgAAKCRAD
ie1tKuOeUJUaAJ0TKvkx1qiJxlAssDkzC+1mElhBJQCgg6tm4u5NCUAbuFosG0Ix
Y34YJ1C5Ag0EUUE/EBAIAJfBCnfQI+/Oy2dLt9RdfsarK0FcsFTFRdiAWEsBoI8l
wPDNamXAqAnGqdZwiVzx26SOmLbveooZmzYGZJV8ouXLSTidpNjoFWyO45XH4Ok8
3b+lJy/JcOSRLBQWrAUaLs46KTWkd0AM+ilegfWrNkcjIbgr7WY64jk640NffRBO
bb/fj+ILpM4keV+8EigC5xWerjC2YR8mnI6P8ylGzeuUitNHToBSf6m3RBEpQxvk
AcKat7BpqJ4cz1+4ACT8RxFL7dAAnnhpbjkM4VHqSjQuf483bVa7dVYZdOA/Ys68
1h9LBBRDbpSl7UPy9s+BRpuTUq8lk69yn6tb63TWATcAAwUH/i7wnh4Vx/0HBYWo
8AjY3iqaIjTW63H70PXKwn7yxLJW2xqSQ2Sre9h9J/arZUwerky3tS3xdcEEGTSP
oXgeg2passygEAnlGUEws2BZ+3XVbSVhh+vMmqOMwz1J1GUKTOWH5vVCsfYdMmb/
4GnxV2iAKeskPRwZFHujaHA0tvlGtRXjFXqxiBuSZjgv0W93sbZQamArCYaJtwT0
2ZgrrUAVEs8JMTbSfrQEmXpfhk2mFcrf2ocAC6LwxMYZESDW6YhlY+1utEqpN6al
Mefh1g42JK2g4OV42iP7op0JeQp6emJFywumlTrnihycRXEElxur+23NSLQpeNaw
M6gUQPeISQQYEQIACQUCUUE/EAIbDAAKCRADie1tKuOeUB+VAJ9e8PprKcX3qvnW
rU8MhhXMB/G0PQCfehvC8uWR/TLtHyu5pjzCEtcsX/E=
=k3yQ
—–END PGP PUBLIC KEY BLOCK—–
3. Decrypt other users file.

To decrypt other users file, It required public key of that user. Import that public key to your account using below command. For example other users public file is otherpub.txt

# gpg –import otherpub.txt
Make sure that file has been imported successfully using below command.

# gpg –list-keys
Above command will show all public key in your account. Make sure the other users public key also exist there.

Now you can decrypt the other users file using below command

# gpg –output otheruserfile.txt otheruserfile.txt.gpg
GPG file encryption command line in Linux

AS we know, now a days it’s not safe to send and receive data over internet. There are many option available to secure your data while traveling over internet. GnuPG also provides you to encrypt your data on key basis. GPG is an encryption and signing tool for UNIX/LINUX like OS.

GnuPG provides many methods for file encryption and decryption.

Method (A): Use Basic GPG encryption

Step 1: First create a file to encrypt using GPG.

# echo “Enter file content here” > secureit.txt
Step 2: Encypt above created file using gpg.

# gpg -c secureit.txt
Above command will create a encrypted file named secureit.txt.gpg. Original file will remain same.

# ls -l
total 8
-rw-r–r– 1 root root 24 Mar 9 21:36 secureit.txt
-rw-r–r– 1 root root 74 Mar 9 21:36 secureit.txt.gpg
Step 3: Finally how to decrypt file again.

# gpg -o secureit-new.txt -d secureit.txt.gpg
gpg: CAST5 encrypted data
Enter passphrase:
You will get a new decypted file named secureit-new.txt.

# ls -l secureit-new.txt
-rw-r–r– 1 root root 24 Mar 9 21:56 secureit-new.txt
Thanks for using this article.

 

 

Configure Caching Name Server on CentOS 6

Configure Caching Name Server on CentOS 6

A caching only DNS server caches DNS query results for the domain name being queried. These chache are stored for pre specified time known as the TTL ( time-to-live )

Step 1: Install the BIND Packages using Yum

Install bind packages using below command. In CentOS/RHEL 6 chaching-nameserver package has been included with bind package.

# yum install bind bind-chroot
Step 2: Copy default bind configuration File

Copy bind configuration file from bind sample files using below command. Change the path of files as per version you have installed.

cd /var/named/chroot/etc
cp /usr/share/doc/bind-9.9.2/sample/etc/named.conf .
cp /usr/share/doc/bind-9.9.2/sample/etc/named.rfc1912.zones .
Step 3: Make changes in Configuration File

Edit bind configuration file in your favorite editor and make necessory changes as per below settings or use below configuration.

// /var/named/chroot/etc/named.conf
options {
listen-on port 53 { 127.0.0.1; any; };
listen-on-v6 port 53 { ::1; };
directory “/var/named”;
dump-file “/var/named/data/cache_dump.db”;
statistics-file “/var/named/data/named_stats.txt”;
memstatistics-file “/var/named/data/named_mem_stats.txt”;
allow-query { localhost; any; };
allow-query-cache { localhost; any; };
recursion yes;

dnssec-enable yes;
dnssec-validation yes;
dnssec-lookaside auto;

/* Path to ISC DLV key */
bindkeys-file “/etc/named.iscdlv.key”;

managed-keys-directory “/var/named/dynamic”;
};

logging {
channel default_debug {
file “data/named.run”;
severity dynamic;
};
};

include “/etc/named.rfc1912.zones”;
Update permissions on configuration files.

# chown root:named named.conf named.rfc1912.zones
Step 4: Check Configuration File

We recommend to check dns configuration file before restarting service.

# named-checkconf named.conf
Step 5: Restart Bind Service

Start Bind (named) service using below command.

# service named restart
Enable auto start bind service on system boot.

# chkconfig named on
Step 6: Finally test Caching Only DNS Setup

Send query to your dns server directly using below command.
Syntax: nslookup < domainname > < caching dns server name/ip >

# nslookup yahoo.com 192.168.1.10
Sample Output:

Server: 192.168.1.11
Address: 192.168.1.11#53

Non-authoritative answer:
Name: yahoo.com
Address: 98.138.253.109
Name: yahoo.com
Address: 98.139.183.24
Name: yahoo.com
Address: 206.190.36.45
If you want to install Master dns server. Follow below link

Check DNS Configuration file ( BIND )

named-checkconf checks the syntax only of a named ( bind ) configuration file. The file is parsed and checked for syntax errors, along with all files included by it. If there are no file is specified with command, /etc/named.conf is read by default.

Tip 1: Check your dns ( bind ) configuration .

In case of any changes done in bind configuration, I recommend to check dns configuration file before restarting service.

# named-checkconf /etc/named.conf
If bind is running in chroot environment use below command also along with above command

# named-checkconf -t /var/named/chroot /etc/named.conf
Above command will show nothing if there are no error found in configuration file. In case of any error will displayed as output.

Tip 2: Check bind zone file using named-checkzone.

To check the syntax of zone file use command as below. It will show result in both cases.

# named-checkzone rmohan.net /var/named/rmohan.net.db
Sample output;

zone rmohan.net/IN: loaded serial 3013040200
OK
Tip 3: Check configuration file in older version of bind.

If you are using older version of bind, you can have also check the configuration using below command.

# service named configtest
Sample Outut:

zone tool.com/IN: loaded serial 42
zone localhost/IN: loaded serial 42
zone 1.168.192.in-addr.arpa/IN: loaded serial 1997022700
zone 0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa/IN: loaded serial 1997022700
zone 255.in-addr.arpa/IN: loaded serial 42
zone 0.in-addr.arpa/IN: loaded serial 42

Master Slave DNS Server on CentOS 6 and RHEL

How to Setup Master Slave DNS Server on CentOS 6 and RHEL

The DNS ( Domain Name System ) is a distributed system, used for transalate domain names to IP and vice a versa. This article will help you to How to Setup Master Slave DNS Server on CentOS 6 and RHEL Systems.

Network Scenario for this Setup:

Master DNS Server IP: 192.168.1.10 ( ns1.rmohan.net )
Slave DNS Server IP: 192.168.1.11 ( ns2.rmohan.net )
Domain Name : rmohan.net ( For Testing Purpose )
Domain IP : 192.168.1.50 ( For Testing Purpose )
Step 1: Install Required RPMS ( at Master and Slave Both )

Install bind packages at both Master and Slave dns servers using following commands.

# yum install bind bind-chroot
Step 2: Setup Master (NS1) DNS Server

There are two types of configuration files in DNS.

One is main dns configuration files named “named.conf”
Another type of configuration file are called zone file. Which is individually created for all domains. named.conf keeps an entry for all zone files.
2.1 Configure named.conf using below configuration

# vim /var/named/chroot/etc/named.conf
Content of named.conf:

// /var/named/chroot/etc/named.conf
options {
listen-on port 53 { 127.0.0.1; 192.168.1.0/24; };
listen-on-v6 port 53 { ::1; };
directory “/var/named”;
dump-file “/var/named/data/cache_dump.db”;
statistics-file “/var/named/data/named_stats.txt”;
memstatistics-file “/var/named/data/named_mem_stats.txt”;
allow-query { localhost; 192.168.1.0/24; };
recursion yes;

dnssec-enable yes;
dnssec-validation yes;
dnssec-lookaside auto;

/* Path to ISC DLV key */
bindkeys-file “/etc/named.iscdlv.key”;

managed-keys-directory “/var/named/dynamic”;
};

logging {
channel default_debug {
file “data/named.run”;
severity dynamic;
};
};

zone “.” IN {
type hint;
file “named.ca”;
};

zone “rmohan.net” IN {
type master;
file “/var/named/rmohan.net.db”;
allow-update { none; };
};

include “/etc/named.rfc1912.zones”;
2.2 Create a zone file for you domain “rmohan.net”

# vim /var/named/chroot/var/named/rmohan.net.db
Content of zone file:

; Zone file for rmohan.net
$TTL 14400
@ 86400 IN SOA ns1.rmohan.net. webmaster.rmohan.net. (
3215040200 ; serial, todays date+todays
86400 ; refresh, seconds
7200 ; retry, seconds
3600000 ; expire, seconds
86400 ) ; minimum, seconds

rmohan.net. 86400 IN NS ns1.rmohan.net.
rmohan.net. 86400 IN NS ns2.rmohan.net.
rmohan.net. IN A 192.168.1.100
rmohan.net. IN MX 0 rmohan.net.
mail IN CNAME rmohan.net.
www IN CNAME rmohan.net.

 

2.3 Add more domains in dns server.
To add more domains in dns, create zone files individually for all domain as above. After that add any entry for all zones in named.conf like below. Change rmohan.net with your domain name.

zone “rmohan.net” IN {
type master;
file “/var/named/rmohan.net.db”;
allow-update { none; };
};
Step 2.4: Start named service .
Start named (bind) service using following command and setup auto start on system boot.

# /etc/init.d/named restart
# chkconfig named on
Step 3: Setup Slave (NS2) DNS Server

At slave dns server you need to update named.conf file only. All zone files will automatically synced from master dns server. Any changes done on Master will reflect on slave after a specified time interval.

3.1 Configure named.conf using below configuration

# vim /var/named/chroot/etc/named.conf
Content of named.conf:

// /var/named/chroot/etc/named.conf
options {
listen-on port 53 { 127.0.0.1; 192.168.1.0/24; };
listen-on-v6 port 53 { ::1; };
directory “/var/named”;
dump-file “/var/named/data/cache_dump.db”;
statistics-file “/var/named/data/named_stats.txt”;
memstatistics-file “/var/named/data/named_mem_stats.txt”;
allow-query { localhost; 192.168.1.0/24; };
recursion yes;

dnssec-enable yes;
dnssec-validation yes;
dnssec-lookaside auto;

/* Path to ISC DLV key */
bindkeys-file “/etc/named.iscdlv.key”;

managed-keys-directory “/var/named/dynamic”;
};

logging {
channel default_debug {
file “data/named.run”;
severity dynamic;
};
};

zone “.” IN {
type hint;
file “named.ca”;
};

zone “rmohan.net” IN {
type slave;
file “slaves/rmohan.net.db”;
masters { 192.168.1.90; };
};

include “/etc/named.rfc1912.zones”;
Step 3.2: Start named Service
Start named (bind) service using below command.

# /etc/init.d/named restart
# chkconfig named on
After restarting named service, Check zone files on slave dns server at /var/named/chroot/var/named/slaves/.

Step 4: Finally Test Your DNS Setup.

Query to your Master and Slave DNS Server directly using following commands, You will get the same resonse from both servers.
Syntax: nslookup <domainname.com> <dns server name/ip>

Query to Master DNS Server:

# nslookup rmohan.net 192.168.1.10

Server: 192.168.1.10
Address: 192.168.1.10#53

Name: rmohan.net
Address: 192.168.1.100
Query to Slave DNS Server:

# nslookup rmohan.net 192.168.1.11

Server: 192.168.1.11
Address: 192.168.1.91#53

Name: rmohan.net
Address: 192.168.1.50
Above outputs is showing that dns server has successfully resolved domain rmohan.net from master and slave dns servers.

 

“tuned” on RHEL/CentOS/Fedora

Starting with RHEL 6 ( and thus also with CentOS 6 ) Red Hat users have possibility to use tuned tool which gives possibility to activate different tuned profiles for RHEL 6 running server.

So what is tuned? ‘yum info tuned’ gives below

# yum info tuned

Description : The tuned package contains a daemon that tunes system settings
: dynamically. It does so by monitoring the usage of several system
: components periodically. Based on that information components will
: then be put into lower or higher power saving modes to adapt to
: the current usage. Currently only ethernet network and ATA
: harddisk devices are implemented.

As description above says,tuned provide daemon to tune system settings dynamically.After installation with

# yum install tuned

in /etc/tune-profiles you will find 9 different profiles designed for different situations.These profiles are

default
desktop-powersave
enterprise-storage
laptop-ac-powersave
laptop-battery-powersave
latency-performance
server-powersave
spindown-disk
throughput-performance

Above default profiles are self descriptive,and if you want to use some of these on your server,I think interesting ones would be

enterprise-storage
latency-performance
server-powersave
throughput-performance

enterprise-storage will configure system parameters which will correspond enterprise class storages – important to mention,it will disable barriers,so not recommended to use it when storage systems do not have battery which prevent data loss in case of power failure

latency-performance is profile designed to provide minimum ( network stack) latency for server.I will edit and adapt parameters related to tpc/udp in /proc/net,do not expect some great magic to happen when switching from default configuration to latency-performance profile

server-powersave is designed with power saving in mind,and in my opinion directed to desktops,not sure why name of profile is server-powersave

throughput-performance will do almost same thing as enterprise-storage but will leave enabled barriers. Recommended is to use it when storage solution is not equipped with battery which prevents data protection in case of power failure

Tuning the Apache Prefork MPM

Apache uses a set of values called the Prefork MPM to determine how many servers it will utilize and how many threads each server can process. Out of the box all Apache installations use the same values regardless of whether your server has 512Mb of RAM or 8Gb of RAM.  It is important that as the server administrator you configure these values to work with your server load.

The Apache Prefork MPM can be found in the Apache configuration file; usually /etc/httpd/conf/httpd.conf.  The default values are…

<IfModule prefork.c>
StartServers       2
MinSpareServers    3
MaxSpareServers    3
ServerLimit       75
MaxClients        75
MaxRequestsPerChild  1000
</IfModule>

Each Directive taken from “http://httpd.apache.org/docs/trunk/mod/mpm_common.html” is detailed below.

– – – – – – – – – – – –

The StartServers directive sets the number of child server processes created on startup.  As the number of processes is dynamically controlled depending on the load there is usually little reason to adjust this parameter.

– – – – – – – – – – – –

The MinSpareServers directive sets the desired minimum number of idle child server processes. An idle process is one which is not handling a request. If there are fewer than MinSpareServers idle then the parent process creates new children until satisfies the MinSpareServers setting.

– – – – – – – – – – – –

The MaxSpareServers directive sets the desired maximum number of idle child server processes. An idle process is one which is not handling a request. If there are more than MaxSpareServers idle, then the parent process will kill off the excess processes.

– – – – – – – – – – – –

The ServerLimit directive is only used if you need to set MaxClients higher than 256 (default). Do not set the value of this directive any higher than what you might want to set MaxClients to.

– – – – – – – – – – – –

The MaxClients directive sets the limit on the number of simultaneous requests that will be served. Any connection attempts over the MaxClients limit will normally be queued, up to a number based on the ListenBacklog directive. Once a child process is freed at the end of a different request, the connection will then be serviced.

For non-threaded servers (i.e., prefork), MaxClients translates into the maximum number of child processes that will be launched to serve requests. The default value is 256; to increase it, you must also raise ServerLimit.

– – – – – – – – – – – –

The MaxConnectionsPerChild directive sets the limit on the number of connections that an individual child server process will handle. After MaxConnectionsPerChild connections, the child process will die. If MaxConnectionsPerChild is 0, then the process will never expire.

Setting MaxConnectionsPerChild to a non-zero value limits the amount of memory that process can consume by (accidental) memory leakage.

– – – – – – – – – – – –

The single most important directive is MaxClients as this determines the amount of Apache child processes that will be launched to server requests.  A simple calculation for MaxClients would be:

(Total Memory – Critical Services Memory) / Size Per Apache process

I define Critical Services as services such as mySQL, Plesk, Cpanel; any service that is required for proper operation of your server.

I’ve used the following commands via shell to determine values for Total Memory, OS Memory, MySQL Memory, and Apache Process Size

TOTAL MEMORY
[root@vps httpd]# free -m
total       used       free     shared    buffers     cached
Mem:          1002        599        402          0         28        337
-/+ buffers/cache:        233        769
Swap:         2047        124       1922

MYSQL MEMORY
[root@vps httpd]# ps aux | grep ‘mysql’ | awk ‘{print $6}’
408
21440
704

APACHE PROCESS SIZE
[root@vps httpd]# ps aux | grep ‘httpd’ | awk ‘{print $6}’
22468
11552
41492
40868
41120
41696
39488
41704
15552
16076
16084
728

In this case the server has 1002Mb of memory allocated, xx used by the OS itself, 21Mb used by mySQL, and each Apache thread averages about 30Mb.

MaxClients = (1002 – 21) / 30 therefore MaxClients = 32.7

The next important aspect is MaxConnectionsPerChild as this is the amount of threads that will be processed before the child is recycled.

A good calculation for MaxConnectionsPerChild would be:

(total amount of daily requests  / total number of daily processes)

Determining these values is a bit more complex as it requires some type of statistics package or thorough knowledge of interpreting Apache access logs.

As this does not adversely effect memory usage, only cpu time to cycle the process if you are unable to determine this information the standard 1000 should be used.

Thus a good configuration for this server would be

<IfModule prefork.c>
StartServers       2
MinSpareServers    3
MaxSpareServers    3
ServerLimit       30
MaxClients        30
MaxRequestsPerChild  1000
</IfModule>

Be sure once you’ve saved the file to perform a configuration test before restarting Apache.

[root@vps httpd]# service httpd configtest
Syntax OK

[root@vps httpd]# service httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd:                                            [  OK  ]

 

 

TCP TUNNING  ON OS LEVEL

 

TCP TUNNING ON OS LEVEL

 

 

net.ipv4.tcp_timestamps=0

net.ipv4.tcp_tw_reuse=1

net.ipv4.tcp_tw_recycle=1

 

net.ipv4.tcp_fin_timeout=30

net.ipv4.tcp_keepalive_time=1800

net.core.rmem_max=8388608

net.core.wmem_max=8388608

 

 

net.core.rmem_default=65536

net.core.wmem_default=65536

net.ipv4.tcp_rmem=’4096 87380 8388608′

net.ipv4.tcp_wmem=’4096 65536 8388608′

net.ipv4.tcp_mem=’8388608 8388608 8388608′

net.ipv4.route.flush=1

net.ipv4.tcp_max_syn_backlog=4096

jvm opts

+AdjustConcurrency
+AggressiveOpts
+AllowJNIEnvProxy
+AllowParallelDefineClass
+AllowUserSignalHandlers
+AlwaysActAsServerClassMachine
+AlwaysCompileLoopMethods
+AlwaysLockClassLoader
+AlwaysPreTouch
+AlwaysRestoreFPU
+AlwaysTenure
+AnonymousClasses
+AssertOnSuspendWaitFailure
+BackgroundCompilation
+BeParanoid
+BindGCTaskThreadsToCPUs
+BlockLayoutByFrequency
+BlockLayoutRotateLoops
+BlockOffsetArrayUseUnallocatedBlock
+BranchOnRegister
+BytecodeVerificationLocal
+BytecodeVerificationRemote
+C1OptimizeVirtualCallProfiling
+C1ProfileBranches
+C1ProfileCalls
+C1ProfileCheckcasts
+C1ProfileInlinedCalls
+C1ProfileVirtualCalls
+C1UpdateMethodData
+CICompilerCountPerCPU
+CITime
+CMSAbortSemantics
+CMSClassUnloadingEnabled
+CMSCleanOnEnter
+CMSCompactWhenClearAllSoftRefs
+CMSConcurrentMTEnabled
+CMSDumpAtPromotionFailure
+CMSExtrapolateSweep
+CMSIncrementalMode
+CMSIncrementalPacing
+CMSLoopWarn
+CMSOldPLABResizeQuicker
+CMSPLABRecordAlways
+CMSParallelRemarkEnabled
+CMSParallelSurvivorRemarkEnabled
+CMSPermGenPrecleaningEnabled
+CMSPrecleanRefLists1
+CMSPrecleanRefLists2
+CMSPrecleanSurvivors1
+CMSPrecleanSurvivors2
+CMSPrecleaningEnabled
+CMSPrintChunksInDump
+CMSPrintObjectsInDump
+CMSReplenishIntermediate
+CMSScavengeBeforeRemark
+CMSSplitIndexedFreeListBlocks
+CMSUseOldDefaults
+CMSYield
+CacheGlobally
+CheckJNICalls
+ClassUnloading
+ClipInlining
+CollectGen0First
+CompactFields
+CompilerThreadHintNoPreempt
+DTraceAllocProbes
+DTraceMethodProbes
+DTraceMonitorProbes
+DeoptimizeRandom
+DisableAttachMechanism
+DisableExplicitGC
+DoEscapeAnalysis
+DontCompileHugeMethods
+DontYieldALot
+DumpSharedSpaces
+EagerXrunInit
+EliminateAllocations
+EliminateAutoBox
+EliminateLocks
+EstimateArgEscape
+ExitOnLargePageFailure
+ExplicitGCInvokesConcurrent
+ExplicitGCInvokesConcurrentAndUnloadsClasses
+ExtendedDTraceProbes
+FLSAlwaysCoalesceLarge
+FailOverToOldVerifier
+FastTLABRefill
+FilterSpuriousWakeups
+ForceNUMA
+ForceSync
+ForceTimeHighResolution
+G1UseAdaptiveConcRefinement
+GCLockerInvokesConcurrent
+GCOverheadReporting
+HeapDumpAfterFullGC
+HeapDumpBeforeFullGC
+HeapDumpOnOutOfMemoryError
+IgnoreUnrecognizedVMOptions
+Inline
+InsertMemBarAfterArraycopy
+JNIDetachReleasesMonitors
+JavaMonitorsInStackTrace
+LIRFillDelaySlots
+LIRSchedule
+LazyBootClassLoader
+LoopUnswitching
+ManagementServer
+MaxFDLimit
+MethodFlushing
+MonitorInUseLists
+MustCallLoadClassInternal
+NUMAStats
+NeedsDeoptSuspend
+NeverActAsServerClassMachine
+NeverTenure
+OmitStackTraceInFastThrow
+OptimizeFill
+OptimizeStringConcat
+OptoBundling
+OptoScheduling
+PSChunkLargeArrays
+ParGCTrimOverflow
+ParGCUseLocalOverflow
+ParallelGCRetainPLAB
+ParallelGCVerbose
+ParallelRefProcBalancingEnabled
+ParallelRefProcEnabled
+PartialPeelAtUnsignedTests
+PartialPeelLoop
+PerfAllowAtExitRegistration
+PerfBypassFileSystemCheck
+PerfDataSaveToFile
+PerfDisableSharedMem
+PostSpinYield
+PreSpinYield
+PreZeroEden
+PreferInterpreterNativeStubs
+PreserveAllAnnotations
+PrintAdaptiveSizePolicy
+PrintCMSInitiationStatistics
+PrintClassHistogram
+PrintClassHistogramAfterFullGC
+PrintClassHistogramBeforeFullGC
+PrintCommandLineFlags
+PrintCompilation
+PrintConcurrentLocks
+PrintFlagsFinal
+PrintFlagsInitial
+PrintGC
+PrintGCApplicationConcurrentTime
+PrintGCApplicationStoppedTime
+PrintGCDateStamps
+PrintGCDetails
+PrintGCTaskTimeStamps
+PrintGCTimeStamps
+PrintHeapAtGC
+PrintHeapAtGCExtended
+PrintHeapAtSIGBREAK
+PrintJNIGCStalls
+PrintJNIResolving
+PrintJavaStackAtFatalState
+PrintOldPLAB
+PrintOopAddress
+PrintPLAB
+PrintParallelOldGCPhaseTimes
+PrintPreciseBiasedLockingStatistics
+PrintPromotionFailure
+PrintReferenceGC
+PrintRevisitStats
+PrintSafepointStatistics
+PrintSharedSpaces
+PrintTLAB
+PrintTenuringDistribution
+PrintTieredEvents
+PrintVMOptions
+PrintVMQWaitTime
+PrintWarnings
+ProfileInterpreter
+ProfileIntervals
+ProfileVM
+ProfilerPrintByteCodeStatistics
+ProfilerRecordPC
+ProtectJavaHeap
+RangeCheckElimination
+ReassociateInvariants
+ReduceBulkZeroing
+ReduceFieldZeroing
+ReduceInitialCardMarks
+ReduceSignalUsage
+ReflectionWrapResolutionErrors
+RegisterFinalizersAtInit
+RelaxAccessControlCheck
+RequireSharedSpaces
+ResizeOldPLAB
+ResizePLAB
+ResizeTLAB
+RestoreMXCSROnJNICalls
+RewriteBytecodes
+RewriteFrequentPairs
+SafepointTimeout
+ScavengeBeforeFullGC
+ShowMessageBoxOnError
+SpecialStringCompareToCC
+SpecialStringCompress
+SpecialStringEqualsCC
+SpecialStringIndexOfCC
+SpecialStringInflate
+SplitIfBlocks
+StackTraceInThrowable
+StartAttachListener
+StressLdcRewrite
+StressTieredRuntime
+SuppressFatalErrorMessage
+SystemMathNatives
+TLABStats
+ThreadPriorityVerbose
+TieredCompilation
+TimeLinearScan
+TraceBiasedLocking
+TraceClassLoading
+TraceClassLoadingPreorder
+TraceClassResolution
+TraceClassUnloading
+TraceGen0Time
+TraceGen1Time
+TraceLoaderConstraints
+TraceMonitorInflation
+TraceParallelOldGCTasks
+TraceSafepointCleanupTime
+TraceSuperWord
+TraceSuspendWaitFailures
+TraceUncommitMemory
+UncommitOldGenOnGC
+UncommitUsesMadvise
+UncommitYoungGenOnGC
+Use486InstrsOnly
+UseAdaptiveGCBoundary
+UseAdaptiveGenerationSizePolicyAtMajorCollection
+UseAdaptiveGenerationSizePolicyAtMinorCollection
+UseAdaptiveNUMAChunkSizing
+UseAdaptiveSizeDecayMajorGCCost
+UseAdaptiveSizePolicy
+UseAdaptiveSizePolicyFootprintGoal
+UseAdaptiveSizePolicyWithSystemGC
+UseAddressNop
+UseAltSigs
+UseAutoGCSelectPolicy
+UseBiasedLocking
+UseBimorphicInlining
+UseBoundThreads
+UseCMSBestFit
+UseCMSCollectionPassing
+UseCMSCompactAtFullCollection
+UseCMSInitiatingOccupancyOnly
+UseCodeCacheFlushing
+UseCompiler
+UseCompilerSafepoints
+UseCompressedOops
+UseCompressedStrings
+UseConcMarkSweepGC
+UseCountLeadingZerosInstruction
+UseCounterDecay
+UseDivMod
+UseFPUForSpilling
+UseFastAccessorMethods
+UseFastEmptyMethods
+UseFastJNIAccessors
+UseFileLocking
+UseG1GC
+UseGCOverheadLimit
+UseGCTaskAffinity
+UseHeavyMonitors
+UseInlineCaches
+UseInterpreter
+UseJumpTables
+UseLWPSynchronization
+UseLargePages
+UseLargePagesIndividualAllocation
+UseLoopCounter
+UseLoopPredicate
+UseMaximumCompactionOnSystemGC
+UseMembar
+UseNUMA
+UseNewLongLShift
+UseNiagaraInstrs
+UseOSErrorReporting
+UseOldInlining
+UseOnStackReplacement
+UseOnlyInlinedBimorphic
+UseOptoBiasInlining
+UsePPCLWSYNC
+UsePSAdaptiveSurvivorSizePolicy
+UseParNewGC
+UseParallelDensePrefixUpdate
+UseParallelGC
+UseParallelOldGC
+UseParallelOldGCCompacting
+UseParallelOldGCDensePrefix
+UsePerfData
+UsePopCountInstruction
+UseRDPCForConstantTableBase
+UseSSE42Intrinsics
+UseSerialGC
+UseSharedSpaces
+UseSignalChaining
+UseSpinning
+UseSplitVerifier
+UseStoreImmI16
+UseStringCache
+UseSuperWord
+UseTLAB
+UseThreadPriorities
+UseTypeProfile
+UseUnalignedLoadStores
+UseVMInterruptibleIO
+UseVectoredExceptions
+UseXMMForArrayCopy
+UseXmmI2D
+UseXmmI2F
+UseXmmLoadAndClearUpper
+UseXmmRegToRegMoveAll
+VMThreadHintNoPreempt
+VerifyMergedCPBytecodes
+WaitForDebugger
+ZeroTLAB
-AdjustConcurrency
-AggressiveOpts
-AllowJNIEnvProxy
-AllowParallelDefineClass
-AllowUserSignalHandlers
-AlwaysActAsServerClassMachine
-AlwaysCompileLoopMethods
-AlwaysLockClassLoader
-AlwaysPreTouch
-AlwaysRestoreFPU
-AlwaysTenure
-AnonymousClasses
-AssertOnSuspendWaitFailure
-BackgroundCompilation
-BeParanoid
-BindGCTaskThreadsToCPUs
-BlockLayoutByFrequency
-BlockLayoutRotateLoops
-BlockOffsetArrayUseUnallocatedBlock
-BranchOnRegister
-BytecodeVerificationLocal
-BytecodeVerificationRemote
-C1OptimizeVirtualCallProfiling
-C1ProfileBranches
-C1ProfileCalls
-C1ProfileCheckcasts
-C1ProfileInlinedCalls
-C1ProfileVirtualCalls
-C1UpdateMethodData
-CICompilerCountPerCPU
-CITime
-CMSAbortSemantics
-CMSClassUnloadingEnabled
-CMSCleanOnEnter
-CMSCompactWhenClearAllSoftRefs
-CMSConcurrentMTEnabled
-CMSDumpAtPromotionFailure
-CMSExtrapolateSweep
-CMSIncrementalMode
-CMSIncrementalPacing
-CMSLoopWarn
-CMSOldPLABResizeQuicker
-CMSPLABRecordAlways
-CMSParallelRemarkEnabled
-CMSParallelSurvivorRemarkEnabled
-CMSPermGenPrecleaningEnabled
-CMSPrecleanRefLists1
-CMSPrecleanRefLists2
-CMSPrecleanSurvivors1
-CMSPrecleanSurvivors2
-CMSPrecleaningEnabled
-CMSPrintChunksInDump
-CMSPrintObjectsInDump
-CMSReplenishIntermediate
-CMSScavengeBeforeRemark
-CMSSplitIndexedFreeListBlocks
-CMSUseOldDefaults
-CMSYield
-CacheGlobally
-CheckJNICalls
-ClassUnloading
-ClipInlining
-CollectGen0First
-CompactFields
-CompilerThreadHintNoPreempt
-DTraceAllocProbes
-DTraceMethodProbes
-DTraceMonitorProbes
-DeoptimizeRandom
-DisableAttachMechanism
-DisableExplicitGC
-DoEscapeAnalysis
-DontCompileHugeMethods
-DontYieldALot
-DumpSharedSpaces
-EagerXrunInit
-EliminateAllocations
-EliminateAutoBox
-EliminateLocks
-EstimateArgEscape
-ExitOnLargePageFailure
-ExplicitGCInvokesConcurrent
-ExplicitGCInvokesConcurrentAndUnloadsClasses
-ExtendedDTraceProbes
-FLSAlwaysCoalesceLarge
-FailOverToOldVerifier
-FastTLABRefill
-FilterSpuriousWakeups
-ForceNUMA
-ForceSync
-ForceTimeHighResolution
-G1UseAdaptiveConcRefinement
-GCLockerInvokesConcurrent
-GCOverheadReporting
-HeapDumpAfterFullGC
-HeapDumpBeforeFullGC
-HeapDumpOnOutOfMemoryError
-IgnoreUnrecognizedVMOptions
-Inline
-InsertMemBarAfterArraycopy
-JNIDetachReleasesMonitors
-JavaMonitorsInStackTrace
-LIRFillDelaySlots
-LIRSchedule
-LazyBootClassLoader
-LoopUnswitching
-ManagementServer
-MaxFDLimit
-MethodFlushing
-MonitorInUseLists
-MustCallLoadClassInternal
-NUMAStats
-NeedsDeoptSuspend
-NeverActAsServerClassMachine
-NeverTenure
-OmitStackTraceInFastThrow
-OptimizeFill
-OptimizeStringConcat
-OptoBundling
-OptoScheduling
-PSChunkLargeArrays
-ParGCTrimOverflow
-ParGCUseLocalOverflow
-ParallelGCRetainPLAB
-ParallelGCVerbose
-ParallelRefProcBalancingEnabled
-ParallelRefProcEnabled
-PartialPeelAtUnsignedTests
-PartialPeelLoop
-PerfAllowAtExitRegistration
-PerfBypassFileSystemCheck
-PerfDataSaveToFile
-PerfDisableSharedMem
-PostSpinYield
-PreSpinYield
-PreZeroEden
-PreferInterpreterNativeStubs
-PreserveAllAnnotations
-PrintAdaptiveSizePolicy
-PrintCMSInitiationStatistics
-PrintClassHistogram
-PrintClassHistogramAfterFullGC
-PrintClassHistogramBeforeFullGC
-PrintCommandLineFlags
-PrintCompilation
-PrintConcurrentLocks
-PrintFlagsFinal
-PrintFlagsInitial
-PrintGC
-PrintGCApplicationConcurrentTime
-PrintGCApplicationStoppedTime
-PrintGCDateStamps
-PrintGCDetails
-PrintGCTaskTimeStamps
-PrintGCTimeStamps
-PrintHeapAtGC
-PrintHeapAtGCExtended
-PrintHeapAtSIGBREAK
-PrintJNIGCStalls
-PrintJNIResolving
-PrintJavaStackAtFatalState
-PrintOldPLAB
-PrintOopAddress
-PrintPLAB
-PrintParallelOldGCPhaseTimes
-PrintPreciseBiasedLockingStatistics
-PrintPromotionFailure
-PrintReferenceGC
-PrintRevisitStats
-PrintSafepointStatistics
-PrintSharedSpaces
-PrintTLAB
-PrintTenuringDistribution
-PrintTieredEvents
-PrintVMOptions
-PrintVMQWaitTime
-PrintWarnings
-ProfileInterpreter
-ProfileIntervals
-ProfileVM
-ProfilerPrintByteCodeStatistics
-ProfilerRecordPC
-ProtectJavaHeap
-RangeCheckElimination
-ReassociateInvariants
-ReduceBulkZeroing
-ReduceFieldZeroing
-ReduceInitialCardMarks
-ReduceSignalUsage
-ReflectionWrapResolutionErrors
-RegisterFinalizersAtInit
-RelaxAccessControlCheck
-RequireSharedSpaces
-ResizeOldPLAB
-ResizePLAB
-ResizeTLAB
-RestoreMXCSROnJNICalls
-RewriteBytecodes
-RewriteFrequentPairs
-SafepointTimeout
-ScavengeBeforeFullGC
-ShowMessageBoxOnError
-SpecialStringCompareToCC
-SpecialStringCompress
-SpecialStringEqualsCC
-SpecialStringIndexOfCC
-SpecialStringInflate
-SplitIfBlocks
-StackTraceInThrowable
-StartAttachListener
-StressLdcRewrite
-StressTieredRuntime
-SuppressFatalErrorMessage
-SystemMathNatives
-TLABStats
-ThreadPriorityVerbose
-TieredCompilation
-TimeLinearScan
-TraceBiasedLocking
-TraceClassLoading
-TraceClassLoadingPreorder
-TraceClassResolution
-TraceClassUnloading
-TraceGen0Time
-TraceGen1Time
-TraceLoaderConstraints
-TraceMonitorInflation
-TraceParallelOldGCTasks
-TraceSafepointCleanupTime
-TraceSuperWord
-TraceSuspendWaitFailures
-TraceUncommitMemory
-UncommitOldGenOnGC
-UncommitUsesMadvise
-UncommitYoungGenOnGC
-Use486InstrsOnly
-UseAdaptiveGCBoundary
-UseAdaptiveGenerationSizePolicyAtMajorCollection
-UseAdaptiveGenerationSizePolicyAtMinorCollection
-UseAdaptiveNUMAChunkSizing
-UseAdaptiveSizeDecayMajorGCCost
-UseAdaptiveSizePolicy
-UseAdaptiveSizePolicyFootprintGoal
-UseAdaptiveSizePolicyWithSystemGC
-UseAddressNop
-UseAltSigs
-UseAutoGCSelectPolicy
-UseBiasedLocking
-UseBimorphicInlining
-UseBoundThreads
-UseCMSBestFit
-UseCMSCollectionPassing
-UseCMSCompactAtFullCollection
-UseCMSInitiatingOccupancyOnly
-UseCodeCacheFlushing
-UseCompiler
-UseCompilerSafepoints
-UseCompressedOops
-UseCompressedStrings
-UseConcMarkSweepGC
-UseCountLeadingZerosInstruction
-UseCounterDecay
-UseDivMod
-UseFPUForSpilling
-UseFastAccessorMethods
-UseFastEmptyMethods
-UseFastJNIAccessors
-UseFileLocking
-UseG1GC
-UseGCOverheadLimit
-UseGCTaskAffinity
-UseHeavyMonitors
-UseInlineCaches
-UseInterpreter
-UseJumpTables
-UseLWPSynchronization
-UseLargePages
-UseLargePagesIndividualAllocation
-UseLoopCounter
-UseLoopPredicate
-UseMaximumCompactionOnSystemGC
-UseMembar
-UseNUMA
-UseNewLongLShift
-UseNiagaraInstrs
-UseOSErrorReporting
-UseOldInlining
-UseOnStackReplacement
-UseOnlyInlinedBimorphic
-UseOptoBiasInlining
-UsePPCLWSYNC
-UsePSAdaptiveSurvivorSizePolicy
-UseParNewGC
-UseParallelDensePrefixUpdate
-UseParallelGC
-UseParallelOldGC
-UseParallelOldGCCompacting
-UseParallelOldGCDensePrefix
-UsePerfData
-UsePopCountInstruction
-UseRDPCForConstantTableBase
-UseSSE42Intrinsics
-UseSerialGC
-UseSharedSpaces
-UseSignalChaining
-UseSpinning
-UseSplitVerifier
-UseStoreImmI16
-UseStringCache
-UseSuperWord
-UseTLAB
-UseThreadPriorities
-UseTypeProfile
-UseUnalignedLoadStores
-UseVMInterruptibleIO
-UseVectoredExceptions
-UseXMMForArrayCopy
-UseXmmI2D
-UseXmmI2F
-UseXmmLoadAndClearUpper
-UseXmmRegToRegMoveAll
-VMThreadHintNoPreempt
-VerifyMergedCPBytecodes
-WaitForDebugger
-ZeroTLAB
AdaptivePermSizeWeight=20
AdaptiveSizeDecrementScaleFactor=4
AdaptiveSizeMajorGCDecayTimeScale=10
AdaptiveSizePausePolicy=0
AdaptiveSizePolicyCollectionCostMargin=50
AdaptiveSizePolicyInitializingSteps=20
AdaptiveSizePolicyOutputInterval=0
AdaptiveSizePolicyWeight=10
AdaptiveSizeThroughPutPolicy=0
AdaptiveTimeWeight=25
AliasLevel=3
AllocatePrefetchDistance=256
AllocatePrefetchInstr=0
AllocatePrefetchLines=3
AllocatePrefetchStepSize=64
AllocatePrefetchStyle=1
AlwaysInflate=0
Atomics=0
AutoBoxCacheMax=128
AutoGCSelectPauseMillis=5000
BCEATraceLevel=0
BackEdgeThreshold=100000
BaseFootPrintEstimate=268435456
BiasedLockingBulkRebiasThreshold=20
BiasedLockingBulkRevokeThreshold=40
BiasedLockingDecayTime=25000
BiasedLockingStartupDelay=4000
BlockLayoutMinDiamondPercentage=20
CICompilerCount=2
CMSAbortablePrecleanMinWorkPerIteration=100
CMSAbortablePrecleanWaitMillis=100
CMSBitMapYieldQuantum=10485760
CMSBootstrapOccupancy=50
CMSClassUnloadingMaxInterval=0
CMSConcMarkMultiple=32
CMSCoordinatorYieldSleepCount=10
CMSExpAvgFactor=50
CMSFullGCsBeforeCompaction=0
CMSIncrementalDutyCycle=10
CMSIncrementalDutyCycleMin=0
CMSIncrementalOffset=0
CMSIncrementalSafetyFactor=10
CMSIndexedFreeListReplenish=4
CMSInitiatingOccupancyFraction=-1
CMSInitiatingPermOccupancyFraction=-1
CMSIsTooFullPercentage=98
CMSLargeCoalSurplusPercent=0.950000
CMSLargeSplitSurplusPercent=1.000000
CMSMaxAbortablePrecleanLoops=0
CMSMaxAbortablePrecleanTime=5000
CMSOldPLABMax=1024
CMSOldPLABMin=16
CMSOldPLABNumRefills=4
CMSOldPLABReactivityCeiling=10
CMSOldPLABReactivityFactor=2
CMSOldPLABToleranceFactor=4
CMSParPromoteBlocksToClaim=16
CMSPrecleanDenominator=3
CMSPrecleanIter=3
CMSPrecleanNumerator=2
CMSPrecleanThreshold=1000
CMSRemarkVerifyVariant=1
CMSRescanMultiple=32
CMSRevisitStackSize=1048576
CMSSamplingGrain=16384
CMSScheduleRemarkEdenPenetration=50
CMSScheduleRemarkEdenSizeThreshold=2097152
CMSScheduleRemarkSamplingRatio=5
CMSSmallCoalSurplusPercent=1.050000
CMSSmallSplitSurplusPercent=1.100000
CMSTriggerPermRatio=80
CMSTriggerRatio=80
CMSWaitDuration=2000
CMSWorkQueueDrainThreshold=10
CMSYieldSleepCount=0
CMSYoungGenPerWorker=16777216
CMS_FLSPadding=1
CMS_FLSWeight=75
CMS_SweepPadding=1
CMS_SweepTimerThresholdMillis=10
CMS_SweepWeight=75
CacheCount=2
ClearFPUAtPark=0
CodeCacheExpansionSize=65536
CodeCacheFlushingMinimumFreeSpace=1536000
CodeCacheMinimumFreeSpace=512000
CompilationPolicyChoice=0
CompilationRepeat=0
CompileCommand=
CompileCommandFile=
CompileOnly=
CompileThreshold=10000
CompilerThreadPriority=-1
CompilerThreadStackSize=0
ConcGCThreads=0
ConditionalMoveLimit=3
DefaultMaxRAMFraction=4
DefaultThreadPriority=-1
DeferPollingPageLoopCount=-1
DeferThrSuspendLoopCount=4000
DesiredMethodLimit=8000
DominatorSearchLimit=1000
EliminateAllocationArraySizeLimit=64
EmitSync=0
ErgoHeapSizeLimit=0
ErrorFile=
EventLogLength=2000
FLSCoalescePolicy=2
FLSLargestBlockCoalesceProximity=0.990000
FenceInstruction=0
FieldsAllocationStyle=1
FreqInlineSize=325
G1ConcRefinementGreenZone=0
G1ConcRefinementRedZone=0
G1ConcRefinementServiceIntervalMillis=300
G1ConcRefinementThreads=0
G1ConcRefinementThresholdStep=0
G1ConcRefinementYellowZone=0
G1ConfidencePercent=50
G1HeapRegionSize=0
G1MarkRegionStackSize=1048576
G1RSetRegionEntries=0
G1RSetScanBlockSize=64
G1RSetSparseRegionEntries=0
G1RSetUpdatingPauseTimePercent=10
G1ReservePercent=10
G1SATBBufferEnqueueingThresholdPercent=60
G1SATBBufferSize=1024
G1UpdateBufferSize=256
GCDrainStackTargetSize=64
GCHeapFreeLimit=2
GCLockerEdenExpansionPercent=5
GCOverheadReportingPeriodMS=100
GCPauseIntervalMillis=0
GCTaskTimeStampEntries=200
GCTimeLimit=98
GCTimeRatio=99
HPILibPath=
HeapBaseMinAddress=4294967296
HeapDumpPath=
HeapFirstMaximumCompactionCount=3
HeapMaximumCompactionInterval=20
InitialCodeCacheSize=2555904
InitialHeapSize=0
InitialRAMFraction=64
InitialSurvivorRatio=8
InitialTenuringThreshold=7
InitiatingHeapOccupancyPercent=45
InlineSmallCode=1000
InteriorEntryAlignment=16
InterpreterProfilePercentage=33
JavaPriority10_To_OSPriority=-1
JavaPriority1_To_OSPriority=-1
JavaPriority2_To_OSPriority=-1
JavaPriority3_To_OSPriority=-1
JavaPriority4_To_OSPriority=-1
JavaPriority5_To_OSPriority=-1
JavaPriority6_To_OSPriority=-1
JavaPriority7_To_OSPriority=-1
JavaPriority8_To_OSPriority=-1
JavaPriority9_To_OSPriority=-1
LargePageHeapSizeThreshold=134217728
LargePageSizeInBytes=0
LoopOptsCount=43
LoopUnrollLimit=60
LoopUnrollMin=4
MarkStackSize=4194304
MarkStackSizeMax=536870912
MarkSweepAlwaysCompactCount=4
MarkSweepDeadRatio=5
MaxBCEAEstimateLevel=5
MaxBCEAEstimateSize=150
MaxDirectMemorySize=-1
MaxGCMinorPauseMillis=18446744073709551615
MaxGCPauseMillis=18446744073709551615
MaxHeapFreeRatio=70
MaxHeapSize=132120576
MaxInlineLevel=9
MaxInlineSize=35
MaxJavaStackTraceDepth=1024
MaxJumpTableSize=65000
MaxJumpTableSparseness=5
MaxLabelRootDepth=1100
MaxLoopPad=11
MaxNewSize=87228416
MaxNodeLimit=65000
MaxPermHeapExpansion=5439488
MaxPermSize=85983232
MaxRAM=137438953472
MaxRAMFraction=4
MaxRecursiveInlineLevel=1
MaxTenuringThreshold=4
MaxTrivialSize=6
MinCodeCacheFlushingInterval=30
MinHeapDeltaBytes=196608
MinHeapFreeRatio=40
MinInliningThreshold=250
MinJumpTableSize=18
MinPermHeapExpansion=327680
MinRAMFraction=2
MinSurvivorRatio=3
MinTLABSize=2048
MonitorBound=0
MultiArrayExpandLimit=6
NUMAChunkResizeWeight=20
NUMAPageScanRate=256
NUMASpaceResizeRate=1073741824
NativeMonitorFlags=0
NativeMonitorSpinLimit=20
NativeMonitorTimeout=-1
NewRatio=7
NewSize=21757952
NewSizeThreadIncrease=5320
NmethodSweepCheckInterval=5
NmethodSweepFraction=4
NodeLimitFudgeFactor=1000
NumberOfLoopInstrToAlign=4
ObjectAlignmentInBytes=8
OldPLABSize=16
OldPLABWeight=50
OldSize=65404928
OnError=
OnOutOfMemoryError=
OnStackReplacePercentage=140
OptoLoopAlignment=16
PLABWeight=75
ParGCArrayScanChunk=50
ParGCDesiredObjsFromOverflowList=20
ParallelGCBufferWastePct=10
ParallelGCThreads=4
ParallelOldDeadWoodLimiterMean=50
ParallelOldDeadWoodLimiterStdDev=80
PartialPeelNewPhiDelta=0
PausePadding=1
PerBytecodeRecompilationCutoff=200
PerBytecodeTrapLimit=4
PerMethodRecompilationCutoff=400
PerMethodTrapLimit=100
PerfDataMemorySize=32768
PerfDataSamplingInterval=50
PerfDataSaveFile=
PerfMaxStringConstLength=1024
PermGenPadding=3
PermMarkSweepDeadRatio=20
PermSize=21757952
PreBlockSpin=10
PreInflateSpin=10
PrefetchCopyIntervalInBytes=576
PrefetchFieldsAhead=1
PrefetchScanIntervalInBytes=576
PreserveMarkStackSize=1024
PretenureSizeThreshold=0
PrintCMSStatistics=0
PrintFLSCensus=0
PrintFLSStatistics=0
PrintSafepointStatisticsCount=300
PrintSafepointStatisticsTimeout=-1
ProcessDistributionStride=4
ProfileIntervalsTicks=100
ProfileMaturityPercentage=20
PromotedPadding=3
QueuedAllocationWarningCount=0
ReadPrefetchInstr=0
ReadSpinIterations=100
RefDiscoveryPolicy=0
ReservedCodeCacheSize=50331648
SafepointPollOffset=256
SafepointSpinBeforeYield=2000
SafepointTimeoutDelay=10000
SelfDestructTimer=0
SharedDummyBlockSize=536870912
SharedMiscCodeSize=4194304
SharedMiscDataSize=4194304
SharedReadOnlySize=10485760
SharedReadWriteSize=14680064
SoftRefLRUPolicyMSPerMB=1000
StackRedPages=1
StackShadowPages=6
StackYellowPages=2
StarvationMonitorInterval=200
SurvivorPadding=3
SurvivorRatio=8
SuspendRetryCount=50
SuspendRetryDelay=5
SyncFlags=0
SyncKnobs=
SyncVerbose=0
TLABAllocationWeight=35
TLABMaxAllocRatio=
TLABRefillWasteFraction=64
TLABSize=0
TLABWasteIncrement=4
TLABWasteTargetPercent=1
TargetPLABWastePct=10
TargetSurvivorRatio=50
TenuredGenerationSizeIncrement=20
TenuredGenerationSizeSupplement=80
TenuredGenerationSizeSupplementDecay=2
ThreadPriorityPolicy=0
ThreadSafetyMargin=52428800
ThreadStackSize=1024
ThresholdTolerance=10
Tier0BackedgeNotifyFreqLog=10
Tier0InvokeNotifyFreqLog=7
Tier0ProfilingStartPercentage=200
Tier1FreqInlineSize=35
Tier1Inline=0
Tier1LoopOptsCount=0
Tier1MaxInlineSize=8
Tier2BackEdgeThreshold=0
Tier2BackedgeNotifyFreqLog=14
Tier2CompileThreshold=0
Tier2InvokeNotifyFreqLog=11
Tier3BackEdgeThreshold=7000
Tier3BackedgeNotifyFreqLog=13
Tier3CompileThreshold=2000
Tier3DelayOff=2
Tier3DelayOn=5
Tier3InvocationThreshold=200
Tier3InvokeNotifyFreqLog=10
Tier3LoadFeedback=5
Tier3MinInvocationThreshold=100
Tier4BackEdgeThreshold=40000
Tier4CompileThreshold=15000
Tier4InvocationThreshold=5000
Tier4LoadFeedback=3
Tier4MinInvocationThreshold=600
TieredCompileTaskTimeout=50
TieredRateUpdateMaxTime=25
TieredRateUpdateMinTime=1
TieredStopAtLevel=4
TraceJVMTI=
TraceRedefineClasses=0
TrackedInitializationLimit=50
TypeProfileMajorReceiverPercent=90
TypeProfileWidth=2
UnguardOnExecutionViolation=0
UseSSE=4
VMThreadPriority=-1
VMThreadStackSize=1024
ValueMapInitialSize=11
ValueMapMaxLoopSize=8
ValueSearchLimit=1000
WorkAroundNPTLTimedWaitHang=1
YoungGenerationSizeIncrement=20
YoungGenerationSizeSupplement=80
YoungGenerationSizeSupplementDecay=8
YoungPLABSize=1024

JVM

JVM parameters set whether you know, here and share with you, including JVMHeap regional distribution, JVM’s two GC threads and Stack set and several other parts, I believe that this introduction to your study will be helpful.

Detailed JVM parameter settings

JVMHeap regional distribution:

JavaHeap is divided into three zones, Young, Old and Permanent. Young district saved vast majority of newly instantiated object, when the area is filled, triggering local GC, GC will Young local area emptied, still referenced objects will be moved to Old area. When the Old district no longer be filled, it will trigger FullGC, finally able to reclaim space recycling. Permanent district stands PermanentGenerationspace, permanent area for the storage of such Class and Method Meta information such Class in the Load when they were placed in the area. It is also responsible for maintaining the other reflective objects, because the reflected object essentially generate some metadata can not be recycled, so that the next reflection reuse.

General Whether local GC (GarbageCollection) or FullGC BE LIABLE PermGenspace to clean up. But if your lot CLASS LOAD Application will then likely overflow error occurs PermGenspace

There are two JVM GC threads:

The first thread is responsible for recycling JVMHeap the Young area.

The second thread in the Heap insufficient, traversal Heap, the Young district upgraded to Older area. Older area equal to the size-Xmx minus the-Xmn,-Xms value can not be set too large, because the second thread is forced to run will reduce the performance of the JVM.

GC may cause frequent causes are:

1, within a program called System. gc () or Runtime. gc ().

2, a number of middleware software call your own GC method, then you need to set parameters ban these GC.

3, Java’s Heap is too small, the general default Heap values ??are very small.

4, the frequent instances of objects, Release object. At this point try to save and reuse objects, such as using StringBuffer () and String ().

If you find that every time the GC, Heap the remaining space will be 50% of the total space, which means you Heap in a healthy state. Many Server side Java program after each GC is best to have 65% of the remaining space.

Server side will suggest the best JVM-Xms and-Xmx to the same value. To optimize the GC, best to let-Xmn-Xmx value is approximately equal to 1/3. A GUI program preferably every 10-20 seconds between run once GC, every half a second to complete. Although it will increase the size of Heap reduce the frequency of GC, but also increase the GC runs every time. And GC runs, all user threads will be suspended, that is, during GC, Java applications do not do any work, which in the GUI interface will very much affect the user experience.

Stack settings

1, each thread has his own Stack.

2,-Xss Stack size specified for each thread

3, Stack size limits the number of threads. Stack too big or too small may cause memory leakage

GC hardware environment also affect the efficiency of such kind of machines, the memory, swap space and CPU quantity. For example: If your program needs to create a lot of frequent transient objects (can not be serialized) will cause the JVM frequent GC. In this case you can increase the machine’s memory, to reduce the Swap space usage.

GC a total of 4 minutes:

1, the first single-threaded GC, is the default GC. The GC is suitable for single-CPU machines.

2, the second is ThroughputGC, is multithreaded GC, for multi-CPU, using a large number of threads the program. The second GC and GC similar to the first, except that the GC in the collection Young area is multi-threaded, but in the Old District, and the first, still single-threaded. -XX: + UseParallelGC parameter to start ThroughputGC.

3, the third is ConcurrentLowPauseGC, similar to the first, for multi-CPU, and require shorter procedures stagnation caused due to GC time. The GC can be recovered in the Old district while running the application. -XX: + UseConcMarkSweepGC parameter to start the GC.

4, the fourth is IncrementalLowPauseGC, for applications that require shortening caused by the program due to stagnation of the time GC. The GC can be recovered in the Young area while recovering a portion of Old Area object. -Xincgc parameter to start the GC.

JVM configuration parameters

1, heapsize

-Xmx

Specifies the maximum jvm heap size, such as:-Xmx = 2G

-Xms

Specifies the minimum jvm heap size, such as:-Xms = 2G, highly concurrent applications, proposals and-Xmx as to prevent shrinkage because of memory / performance impact of a sudden increase.

-Xmn

Specifies the size of the jvm YoungGeneration, such as:-Xmn256m. This parameter is affecting performance, if your program requires more temporary memory, it is recommended to set to 512M, if less, to minimize this value, generally 128/256 is sufficient to use.

Specify the jvm PermGeneration minimum, such as:-XX: PermSize = 32m. This parameter need to see your actual situation. You can see in the end how much jmap command.

Specifies the maximum PermGeneration, such as:-XX: MaxPermSize = 64m

-Xss

Zhan specified thread size, such as:-Xss128k, in general, webx framework application requires 256K. If your application has a large-scale recursive behavior, consider setting to 512K/1M. This requires comprehensive testing to know. However, 256K has been great. This parameter has the greatest impact on performance.

Specify the jvm OldGenerationheapsize with NewGeneration ratio in the case of using this parameter CMSGC failure, such as:-XX: NewRatio = 2 (default)

Specify NewGeneration in EdenSpace with a SurvivorSpace proportion of heapsize,-XX: SurvivorRatio = 8, then a total of 10M NewGeneration case, EdenSpace of 8M

Specifies jvmheap In the case of usage is less than n, heap shrink, Xmx == Xms invalid case, as:-XX: MinHeapFreeRatio = 30

Specifies jvmheap the usage case is greater than n, heap for expansion, Xmx == Xms invalid case, as:-XX: MaxHeapFreeRatio = 70

Specifies the Java heap pagination page size, such as 128M

2, garbagecollector

-XX: + UseParallelGC

Specifies YoungGeneration use parallelcollector, parallel collector, pause appthreads, simultaneously start multiple garbage collection thread, can not CMSGC together. The amount of system t spit priority, but there will be a long long time apppause, background system task can use this GC

Specify parallelcollection thread started when the number, the default is the number of physical processor

-XX: + UseParallelOldGC

Specifies OldGeneration use parallelcollector

-XX: + UseParNewGC

Specifies NewGeneration use parallelcollector, the GC is UseParallelGC upgraded version has better performance or merit, can be used together CMSGC

-XX: + CMSParallelRemarkEnabled

In the case of using UseParNewGC minimize mark time

-XX: + UseConcMarkSweepGC

Specifies OldGeneration use concurrentmarksweepGC, GCthread and Appthread parallel (in init-mark and remark when pauseappthread). apppause short time, a system for strong interaction, such as webserver

-XX: + UseCMSCompactAtFullCollection

In the case of using concurrentGC prevent memoryfragmention, to organize the liveobject that reduce memory fragmentation

Indicates oldgeneration n% in the use of the scale, the start concurrentcollector, the default value is 68, such as:-XX: CMSInitiatingOccupancyFraction = 70

-XX: + UseCMSInitiatingOccupancyOnly

Instructions in the use of only oldgeneration proportion initialization after concurrentcollector start collecting

3, others

Specify an object experiencing n times YoungGC and transferred to oldgeneration area, linux64 under the java6 default value is 15, this parameter is not valid for throughputcollector, such as:-XX: MaxTenuringThreshold = 31

-XX: + DisableExplicitGC

Prohibit java program FullGC, such as System. gc () call. Best to add code to prevent misuse of the program impact on performance.

-XX: + UseFastAccessorMethods

get, set method to native code switch

-XX: + PrintGCDetails

Should fight the case, such as garbage collection:

953935K (2070976K), 0.0196420secs]

-XX: + PrintGCTimeStamps

Playing time garbage collection should be the case, such as:

[Times: user = 0.09sys = 0.00, real = 0.02secs]

-XX: + PrintGCApplicationStoppedTime

Fight should refuse collection, the system pause time, such as: Totaltimeforwhichapplicationthreadswerestopped: 0.0225920seconds
Source: Network