Tuesday, August 30, 2011

Unix File Permissions



When ever I discussed some issue related to file access, most people didn't have a clear understanding what it means, when u see file permissions as -rw-r--r--. Or how it is different from drw-r--r-x

As a developer, I always need to know this when I have to look and debug issues on dev/qa/prod servers running on linux. Based on my experience, in this tutorial, I'll clarify the concepts involved.

ls -l
total 160
-rwxrwxrwx   1 ashishsharma3  staff   1040 May  5 13:10 deploy.sh
drwxrwxrwx   5 ashishsharma3  staff    170 May  5 13:04 hcmscripts
-rw-r--r--   1 ashishsharma3  staff  50267 Aug 24 13:11 pom.xml
-rwxrwxrwx   1 ashishsharma3  staff    211 May  5 13:06 realestate-fe-test.recipe


Understanding Position
In say -rw-r--r--, what is at what position

1	directory flag, 'd' if a directory, '-' if a normal file
2,3,4	read, write, execute permission for User (Owner) of file
5,6,7	read, write, execute permission for Group
8,9,10	read, write, execute permission for Other

Understanding values

-	in any position means that flag is not set
r	file is readable by owner, group or other
w	file is writeable. On a directory, write access means you can add or delete files
x	file is executable (only for programs and shell scripts - not useful for data files). Execute permission on a directory means you can list the files in that directory
s	in the place where 'x' would normally go is called the set-UID or set-groupID flag.

For a directory, the set-groupID flag means that all files & subdirectories created inside that directory will inherit the group of the directory. 
Otherwise, a file takes on the primary group of the user creating the file. 

Octal Text Binary Meaning
0	---	000	All types of access are denied
1	--x	001	Execute access is allowed only
2	-w-	010	Write access is allowed only
3	-wx	011	Write and execute access are allowed
4	r--	100	Read access is allowed only
5	r-x	101	Read and execute access are allowed
6	rw-	110	Read and write access are allowed
7	rwx	111	Everything is allowed

Easiest way to remember - It is always in order rwx

r = 100 = 4
w = 010 = 2
x = 001 = 1

Triplet for u: rwx => 4 + 2 + 1 = 7
Triplet for g: r-x => 4 + 0 + 1 = 5
Tripler for o: r-x => 4 + 0 + 1 = 5
Which makes -rwxr-xr-x: 755

chmod [options] mode file(s)

chmod -R 777 mydir

-R = recursive, affects the subdirectories and files as well.

chmod 100 myfile

chmod g+rwxs mydir
give full group read/write access to directory "mydir", also setting the set-groupID flag so that directories created inside it inherit the group 


chmod g-rw myfile
remove read and write access to "myfile", leaving all other permission flags alone 

chmod -R g+rw .
give group read write access to this directory, and everything inside of it (-R = recursive) 



Unix commands for Developers


This article is in continuation to -


Unix Grep Commands for Developers
Unix Find Commands for Developers
Unix Network Commands for Developers
Unix File Permissions


Please make sure you get an understanding of the concepts in these articles before reading further.


###########################################################


list all the links in a directory


ls -ltR | grep ">"


###########################################################


create a read only file


touch filename
chmod 400 filename


if file is already created and we do 
touch filename


it changes the modified timestamp to now.


###########################################################


Running a background process (Deamon)- use '&' in end of command


./import_data.sh &


java MyClass &


###########################################################


Dumping the Output of a process to a file


java MyClass > logFile.txt


./import_data.sh > log.txt


note: space between command and file name ' > log.txt'


./import_data.sh param1 param2 > log.txt &


nohup 
- command to ignore the HUP (hangup) signal, enabling the command to keep running after the user who issues the command has logged out. The HUP (hangup) signal is by convention the way a terminal warns depending processes of logout.


nohup ./import_data.sh param1 param2 > log.txt &


###########################################################


To see if process is running


ps -eaf | grep someTextInProcess


ps -eaf | grep import_
ps -eaf | grep myClass


###########################################################


History of cmds executed


history


Search for specific commands in history


history | grep "somethingFromPastCmd"


###########################################################


disk free


display the amount of available disk space for filesystems, on which the invoking user has appropriate read access


df


df [-k] [file...]


k = kilo
h = human redable. It is in K,M,G. K=kilo, M=mega,G=Giga
file = amount of free space of the file system containing the specified file
which directory is taking how much space


###########################################################


Disk Usage


estimate file space usage—space used under a particular directory or files on a file system.


gives the total size of current dir


du –sh


gives the total size, folder wise and file wise (files present directly in that directory)


du -sk *


Disk usage of all subdirectories and files including hidden files within the current directory (sorted by filesize) :


$ du -sk .[!.]* *| sort -n


Disk usage of all subdirectories and files including hidden files within the current directory (sorted by reverse filesize) :


$ du -sk .[!.]* *| sort -nr


###########################################################


Synbolic Links


-------
Create
-------


-
Soft link -
-
If the original program, file, or directory is renamed, moved, or deleted, the soft link is broken


ln -s directoryTo linkName


-
Hard link -
-
Unix Hard links are pointers to programs and files, but NOT directories
If the original program or file is renamed, moved, or deleted, the hard link is NOT broken
Hard links in UNIX cannot span disk drives,


ln myfile mylink


-------
Update
-------


ln -nsf newDirectory existingLinkName


-------
Delete
-------


rm -rf linkName


###########################################################


Zombie Process: 


The process is dead but have not been removed from the process table.


If you do 'ps', the child will have a 'Z' in its status field to indicate this


###########################################################


export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
export PATH=$PATH:$JAVA_HOME


set it in ~/.bashrc OR ~/.prifile


###########################################################


32 bit or 64 bit ?
"uname -a"


###########################################################


Substitute - Find and replace


Replace words in a file


sed s/OldWord/NewWord/g fileName.


s stands for substitute


sed s/day/night/ oldFileName > newFileName




Using & as the matched string


echo "123 abc" | sed 's/[0-9]*/& &/'
123 123 abc


sed 's/[a-z]*/(&)/' oldFileName > newFileName


sed s/[0-9]*/'& & &'/g myfile.txt


d command to delete lines 
delete lines that are either blank or only contain spaces:
sed '/^ *$/d' inputFileName 




###########################################################


ftp


http://www.cs.colostate.edu/helpdocs/ftp.html


To connect your local machine to the remote machine, type


ftp machinename


When you enter your own loginname and password for the remote machine, it returns the prompt


ftp>


and permits you access to your own home directory on the remote machine.


commands


-------------------
to delete (remove) a file in the current remote directory (same as rm in UNIX)


delete fileName


-------------------


to copy one file from the remote machine to the local machine


get fileName


-------------------


to make a new directory within the current remote directory


mkdir dir


-------------------


to copy multiple files from the remote machine to the local machine;
you are prompted for a y/n answer before transferring each file


mget ABC DEF
mget *


-------------------
to copy one file from the local machine to the remote machine


put fileName


-------------------
mput ABC DEF


to copy multiple files from the local machine to the remote machine;
you are prompted for a y/n answer before transferring each file
-------------------


quit   to exit the FTP environment (same as bye)




###########################################################


NUMBER OF LINES IN A FILE


wc -l fileName


SHOW ONLY FEW LINES FROM FILE


less fileName


NUMBER OF SPECIFIC WORDS IN FILE


grep "word" <filename> | wc -l
grep www.google.com/bot.html access_log | wc -l


- put quotes around the word if it has spaces


###########################################################


=== copy files to remote host ===


syntax-
scp files user@remote.hostname:/path_to_copy_file


examples-


a) Copy from current to remote -


scp *.txt user@remote.server.com:/home/user/
 -This will copy all files with .txt extension to the directory /home/user in the remote.server.com host


b) Copy from remote to current  -


scp -r miguel@10.1.2.2:/home/myfolder/ ashish@10.1.2.3:/home/myfolder/
- This is going to recursively copy all files from myfolder's directory on 10.1.2.2 host to his myfolder directory in 10.1.2.3 host.


-r is to copy the entire directory


Sometimes while copying files from prod to dev does not work when u are logged in prod and try (a) - due to firewall/security settings. Then (b) helps by logging on local dev and trying to copy from remote.


Note : To use this command you need to have open-ssh installed in the hosts.


###########################################################


vi myFile.txt


- before entering data, enable insert mode - by pressing I
- to save after edit --- esc + !wq + enter
- to delete a line --- esc + press D twice for one line


SEE FIRST OCCURANCE OF A WORD IN FILE


vi file
/<word>


SEE LAST OCCURANCE OF A WORD IN FILE


vi file
?<word>


after the word is found, go to next word
press n


Go to end of file


G


Capital G


/s/oldWord/newWord/g - replace all occurrences



/s/oldWord/newWord - replace first occurrenc, then have to press n to go to next and replace


###########################################################


Sort


ls -s | sort -n


the the contents in a file alphabaticallt


sort myfile


Sort Decsending
sort -r myfile


###########################################################
cat 


to display file or concatenate files
cat filename


###########################################################


JAVA


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--- COMPILE ---
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


javac -cp . Test.java




~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--- RUN ---
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


- you can add entire directory in classpath -- ../lib;
- only specify classname like MyJavaClass.. not the extention like MyJavaClass.class
- space separated entries after classname are String[] args that get supplied as params to main() method
- if have folder structure in java packacge like myfolder.mypackage.MyJavaClass. Then maintain the same physical folder/directory structure in my_job.jar.




--------------------
~~~ In WINDOWS ~~~~
--------------------


java -Xms2G -Xmx4G -cp .;../lib/mysql-connector-java-5.1.0-bin.jar;../lib/mq.jar;my_job.jar;../lib; myfolder.mypackage.MyJavaClass param1 param2


- all items in classpath are semi-colon separated


--------------------
~~~ In UNIX ~~~~
--------------------




java -Xms2G -Xmx4G -cp .:../lib/mysql-connector-java-5.1.0-bin.jar:../lib/mq.jar::my_job.jar:../lib: myfolder.mypackage.MyJavaClass param1 param2


- all items in classpath are colon separated.


###########################################################


Monday, August 29, 2011

Unix Network Commands for Developers

I recently was working with a partner company where we have make few connections to their servers. These few utilities that I am listing down, helped me a lot while debugging network, connection issues.

So, here I am sharing basic + advanced utilities that i used -

###########################################################

Finding host/domain name

hostname

###########################################################

Test network connection

ping

It sends packets of information to the user-defined source. If the packets are received, the destination device sends packets back. Ping can be used for two purposes

1. To ensure that a network connection can be established.
2. Timing information as to the speed of the connection.

###########################################################

Network configuration

ifconfig

###########################################################

Connections to and from the host

netstat

netstat -a will display all connections including TCP  and UDP  
netstat –t will display only TCP  connection
netstat –u will display only UDP  connection

###########################################################

DNS lookup name - ip address to hostname, hostname to ip

nslookup

nslookup blogger.com

###########################################################

Communicate with other hostname on specific port

telnet

telnet hostname port   will telnet hostname with the port specified. Normally it is used to see whether host is alive and network connection is fine or not.

###########################################################

view current user's information - user’s login name, real name, terminal name and write status.

finger

###########################################################

Outing steps that packets take to get to network host - hop by hop, starting from your home router to inter provider's servers to ... actual host.

traceroute

traceroute http://realestate.aol.com/homes-for-sale-listings/Austin_TX
traceroute: Warning: http://realestate.aol.com/homes-for-sale-listings/Austin_TX has multiple addresses; using 8.15.7.117
traceroute to http://realestate.aol.com/homes-for-sale-listings/austin_tx (8.15.7.117), 64 hops max, 52 byte packets
 1  wireless_broadband_router (192.168.1.1)  0.801 ms  0.696 ms  0.577 ms
 2  l100.clppva-vfttp-15.verizon-gni.net (173.71.222.1)  11.506 ms  19.462 ms  11.094 ms
 3  g9-2-115.clppva-lcr-01.verizon-gni.net (130.81.129.38)  11.722 ms  11.892 ms  9.686 ms
 4  p13-0-0.clppva-lcr-02.verizon-gni.net (130.81.23.0)  154.065 ms  77.945 ms  28.307 ms
 5  so-10-0-0-0.res-bb-rtr2.verizon-gni.net (130.81.28.14)  15.989 ms  14.192 ms  9.498 ms
 6  0.ae2.br2.iad8.alter.net (152.63.34.73)  65.482 ms
    0.ae2.br1.iad8.alter.net (152.63.32.158)  21.324 ms  21.618 ms
 7  * * *
 8  vlan51.ebr1.washington12.level3.net (4.69.146.190)  18.748 ms  15.170 ms  9.677 ms
 9  ae-8-8.ebr1.washington1.level3.net (4.69.143.217)  16.840 ms  21.552 ms  19.912 ms
10  ae-91-91.csw4.washington1.level3.net (4.69.134.142)  19.294 ms  22.256 ms
    ae-61-61.csw1.washington1.level3.net (4.69.134.130)  12.568 ms
11  ae-44-90.car4.washington1.level3.net (4.69.149.198)  23.055 ms
    ae-34-80.car4.washington1.level3.net (4.69.149.134)  13.068 ms
    ae-24-70.car4.washington1.level3.net (4.69.149.70)  18.771 ms
12  co-location.car4.washington1.level3.net (4.79.170.254)  20.788 ms  21.715 ms  18.423 ms
13  64.158.56.34 (64.158.56.34)  13.092 ms  20.214 ms  9.067 ms

###########################################################

Unix Find Commands for Developers


Unix's find command searches through one or more directory trees of a file system, locates files based on some criteria.


Here I am listing down some of the way I use find command regularly


###########################################################


find directory -name fileName


###########################################################


Finding files which has been modified less than one day in Unix:


find dir -mtime -1


###########################################################


List all the files & directories in current directory with permission-


find dir -perm 777


###########################################################


Case Insensative


find dir –iname fileNaMe


###########################################################


Find and Delete


find dir -name "*.tmp" | xargs rm -rf


xargs along with find allows to whatever with each search result


find dir -name filename | xargs grep "word"


###########################################################


Find files with size


find dir -size +10000c -size -50000c
find . -size +100k -size -500k


Use c after the number, and specify the size in bytes. Or use k.
The minus sign means "less than," and the plus sign means "greater than


find . -mtime +10 -size +50000c


###########################################################


Files Only


find . -name "my*" -type f


type can be f, d, l -- files, dirs, links


###########################################################


Suppress lines that contain permission denied errors.


find . -name "myfile" | xargs grep -v "Permission denied"


###########################################################


Execute an Action


find dir -name "*.mp3" -type f -exec chmod 644 {} \;


This command changes the permissions of all files with a name ending in .mp3 in the directory dir. 
The action is carried out by specifying the option -exec chmod 644 {} \; in the command. 
For every file whose name ends in .mp3, the command chmod 644 {} is executed replacing {} with the name of the file. 
The semicolon (backslashed to avoid the shell interpreting it as a command separator) indicates the end of the command


find . -exec grep blah {} ;
This is just an example, it is more efficient to pipe the results to the xargs command instead.


###########################################################


find /Users/ashishsharma3/ -iname "Doc*" -mtime -1 -perm 777 -size +100k -size -500k -type f | xargs grep "blah"

find /Users/ashishsharma3/ -iname "Doc*" -mtime -1 -perm 777 -size +100k -size -500k -type f | xargs rm -rf


find /Users/ashishsharma3/ -iname "Doc*" -mtime -1 -perm 777 -size +100k -size -500k -type f -exec chmod 555 {} \;

Unix Grep Commands for Developers


I was trying to find an entry in a txt file, but I didn't knew the exact file name and where it was located. This is where find & grep came together and helped me -

 find / -name "*.txt" | xargs grep "sitemap"


To find only unique occurrences of a pattern in a file


grep word myfile.txt | sort | uniq


sort - sorts the matches in natural order, and when sorted order piped with uniq -> gives only the unique matches


grep '400' me.txt | sort | uniq | grep -o http://[^[:space:]]*

The above command find only unique urls with 400 errors
-o returns only matches, and not the whole line.


Many people use grep just for finding words in a file and miss the real potential of grep. It has saved a lot of time when I have to analysis over some log files in production.

Based on my experience, here I am listing what I use the most -


###########################################################
Match a pattern (regular expression). Lists Filename with matched line.

grep matchPattern myfile.txt

To match COMPLETE line



grep smug files{search files for lines with 'smug'}
grep '^smug' files{'smug' at the start of a line}
grep 'smug$' files{'smug' at the end of a line}
grep '^smug$' files{lines containing only 'smug'}
grep '\^s' files{lines starting with '^s', "\" escapes the ^}
grep '[Ss]mug' files{search for 'Smug' or 'smug'}
grep 'B[oO][bB]' files{search for BOB, Bob, BOb or BoB }
grep '^$' files{search for blank lines}
grep '[0-9][0-9]' file{search for pairs of numeric digits}



To match a WORD in a line




grep '^From: ' /usr/mail/$USER{list your mail}
grep '[a-zA-Z]'{any line with at least one letter}
grep '[^a-zA-Z0-9]{anything not a letter or number}
grep '[0-9]\{3\}-[0-9]\{4\}'{999-9999, like phone numbers. Like in java we use [a-z]{3,}}
grep '^.$'{lines with exactly one character}
grep '"smug"'{'smug' within double quotes}
grep '"*smug"*'{'smug', with or without quotes}
grep '^\.'{any line that starts with a Period "."}
grep '^\.[a-z][a-z]'{line start with "." and 2 lc letters}




###########################################################
Match text. Lists Filename with matched line.

grep "this world is" myfile.txt


###########################################################
Match exact word

grep -w word myfile


###########################################################



Count
 of a particular word in file

grep -c "word" myfile


###########################################################




Case Insensitive

grep -i "Word" myfile


###########################################################

See line numbers of matching lines

grep -n word myfile


###########################################################



Show matches with as colored

grep word myfile --color


###########################################################
Finding relevant word and exclusion irrelevant word.

grep Exception logfile.txt | grep -v ERROR


###########################################################
Print also lines around matched word's line. E.g. 2 lines -

grep -C 2 "word" myfile


###########################################################
Match either this OR that. Using egrep -

egrep "Exception|Error" myfile


###########################################################

Match through gzipped *.gz files. Using zgrep -

zgrep -i "Word" myfile.gz


###########################################################
Only give the filenames of matched files

grep -l word myfile


###########################################################

Thursday, August 25, 2011

Java Nested Inner Classes

Nested Classes

The Java allows to define a class within another class. Such a class is called a nested class a

Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

class OuterClass {
		...
		
		static class StaticNestedClass {
			...
		}
		
		...
		
		class InnerClass {
			...
		}
		
		...
	}

A nested class is a member of its enclosing class.

Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.

Static nested classes do not have access to other members of the enclosing class.

As a member of the OuterClass, a nested class (static and non-static) can be declared private, public,protected, or package private. (Recall that outer classes can only be declared public or package private.)

Why Use Nested Classes?

It is a way of logically grouping classes that are only used in one place.
It increases encapsulation. Example: kind of entry class in hashmap.
Nested classes can lead to more readable and maintainable code.

Static Nested Classes

A static nested class is just like any other top-level class.

It cannot access variables and members of outer class directly.

Only way to interact with the instance members of its outer class (and other classes) just like any other top-level class - but creating an object of outer class and then accessing its members and variables.

For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Inner Classes

It has direct access to outer object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Additionally, there are two special kinds of inner classes: local classes and anonymous classes (also called anonymous inner classes).

Local and Anonymous Inner Classes

There are two additional types of inner classes. You can declare an inner class within the body of a method. Such a class is known as a local inner class. You can also declare an inner class within the body of a method without naming it. These classes are known as anonymous inner classes.

public class MyClass {
	public A myFunction() {
		return new A() {
			private int i = 11;

			public int getValue() {
				return i;
			}
		}; // Semicolon required in this case
	}

	public static void main(String[] args) {
		MyClass p = new MyClass();
		A c = p.myFunction();
	}
}

interface A {
	int getValue();
}




package main.java.concepts;


// wrong - >
// import main.java.algo.faaltoo;
// imports are checked and validated at compile time.

	//	Why Use Nested Classes?
	//
	//		It is a way of logically grouping classes that are only used in one place.
	//		It increases encapsulation. Example: kind of entry class in hashmap.
	//		Nested classes can lead to more readable and maintainable code.


// fyi - top level class can be only public OR default
// and name of top level class is the name of .java file
public class NestedInnerClasses {
	
	public static void main(String[] args) {
		OuterClass outerObj = new OuterClass();
		
		// A nested class is a member of its enclosing class.
		
		// instantiate static nested
		OuterClass.StaticNestedClass statNestClass = new OuterClass.StaticNestedClass();
		
		//instantiate non-static inner
		OuterClass.InnerClass innerClass = outerObj.new InnerClass();
	}
	
	
	// anonymous local classes
	public ABC getAnon() {
		
		return new ABC() {
			public int getVal() {
				return 0;
			}
		}; // semi-colon required
		
	}
	
}

interface ABC {
	public int getVal();
}


class OuterClass {
	
	private int outerPrivVal = 10;
	public int outerPubVal = 20;
	
	private void outerPricFxn() {
		System.out.println("In Outer Private Function");
	}
	
	public void outerPubFxn() {
		System.out.println("In Outer Public Function");
	}
	
	public void doJob() {
		OuterClass.StaticNestedClass statNestClass = new StaticNestedClass();
	}
	
	// static nested classes are just like any top level class
	// Static nested classes do not have access to other members of the enclosing class.
	// Only way to access it is via object of Outer, just like any other top level class.
	// via object, it can access even private members. This is not possible via any top level class. Can be only done in nested static class.
	static class StaticNestedClass {
		
		public void staticNestedClassFxn() {
			OuterClass outerObj = new OuterClass();
			outerObj.outerPrivVal = 13;
			outerObj.outerPubVal = 23;
			outerObj.outerPricFxn();
			outerObj.outerPubFxn();
		}
		
	}
	
	// inner class can access all members of outer class
	// this class can be public/private/protected/dafault - but if private - cannot be accessed outside outerclass. - if protected, cannot be accessed outside this pkg and any classes extending outer.
	class InnerClass {
		
		public void innerClassFxn() {
			outerPrivVal = 15;
			outerPubVal = 25;
			outerPricFxn();
			outerPubFxn();
		}
		
	}
	
}


References -

http://download.oracle.com/javase/tutorial/java/javaOO/nested.html

Basics: Java's public private protected default

public : Accesible everywhere. Any package. Any class.

private : Accessible only within the same class.

protected : Let class ABC declares something as protected. Then it is accessible to all classes in same package as ABC. Plus any class in any package, extending class ABC.

default : without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.

Note: A class class can be private or protected, ONLY if it is a Nested/Inner class, otherwise it has to be public (if top level class) OR default.

public class Test {

    private class NestedClass {
       
    }
   
}


Wednesday, August 24, 2011

Understanding Java Garbage Collection and its algorithms.


Here is a deeper dive into - Understanding Java Garbage Collection and its algorithms.

This article is in continuation to my article on "Understanding Java Heap Space and Memory Tuning". Make sure you understand the concepts behind Java heap usage before diving into garbage collection details.

We cannot force Garbage Collection, but could request it by calling System.gc() or Runtime.gc().

JVM does not guarantee that GC will be started immediately. Also, Garbage collection does not guarantee that a program will not run out of memory.

JVM automatically removes the unused variables/objects from the memory... to create free space for the programs that are currently running.

Garbage Collection runs on Heap and NOT stack

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. We usually nullify the object references of large objects like collections, maps etc in the finalize block.

An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.

An object's finalize() method may only be invoked once by the garbage collector.

A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected. The system will not do it and you cannot force it either.

An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

GC is a daemon thread that runs in JVM

How does an object become eligible for GC

1. All available object references are null
2. When parent Object references become null, all child objects (objects references in other object) also become eligible for GC
3. Make the reference variable to refer to another object and neither of the objects is referenced by any other object. That's an island of isolation. Basically, an island of isolation is a group of objects that reference each other but they are not referenced by any active object in the application

Various types of Garbage collection Java which can be used by passing params to the JVM via executing a java program.

-XX:+UseParallelGC
version of the young generation collector

-XX:+UseConcMarkSweepGC
collect the tenured generation

When GC happens, it may run parallel to the application or can pause the application for times when GC is done.

UseParallelGC : Young Generation is partially and parallel'ly collected. It is a minor collection & carried in parallel to executing code and is not much of a performance impact. When it performs a minor GC, the VM moves any remaining objects from the eden space to one of the survivor spaces. The VM moves objects that live long enough in the survivor spaces to the "tenured" space in the old generation.

UseConcMarkSweepGC : This is a full GC and application pauses while it runs. It is a performance heavy. When the old generation fills up, there is a full GC that is often much slower because it involves all live objects.