Wednesday, May 6, 2015

MongoDB Few Basic Commands and Queries

MongoDB

MongoDB Create Database
use Command
MongoDB use DATABASE_NAME is used to create database. The command will create a new database, if it doesn't exist otherwise it will return the existing database.
Syntax:
use DATABASE_NAME
Example:
>use mydb=========here mydb is database name
To check current database
>db
This will show current working db
To show all databases
>show dbs
MongoDB Drop Database
dropDatabase() Method
MongoDB db.dropDatabase() command is used to drop a existing database.
Basic syntax of dropDatabase() command is as follows:
db.dropDatabase()


MongoDB Create Collection



createCollection() Method
MongoDB db.createCollection(name, options) is used to create collection.
Basic syntax of createCollection() command is as follows
db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and used to specify configuration of collection


Parameter Type Description
Name String Name of the collection to be created
Options Document (Optional) Specify options about memory size and indexing




Options parameter is optional, so you need to specify only name of the collection. Following is the list of options you can use:
EXAMPLES:
Basic syntax of createCollection() method without options is as follows
>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>
You can check the created collection by using the command show collections
>show collections========this will show list collections in ur db




Following example shows the syntax of createCollection() method with few important options:


>db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } )
{ "ok" : 1 }


> In mongodb you don't need to create collection. MongoDB creates collection automatically, when you insert some document.


>db.tutorialspoint.insert({"name" : "tutorialspoint"})
>show collections
mycol
mycollection
system.indexes
tutorialspoint

MongoDB Drop Collection





drop() Method
MongoDB's db.collection.drop() is used to drop a collection from the database.
db.COLLECTION_NAME.drop()
EXAMPLE:
First, check the available collections into your database mydb
>use mydb
switched to db mydb
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
Now drop the collection with the name mycollection


>db.mycollection.drop()
true
>

MongoDB Datatypes

MongoDB supports many datatypes whose list is given below:


String : This is most commonly used datatype to store the data. String in mongodb must be UTF-8 valid.


Integer : This type is used to store a numerical value. Integer can be 32 bit or 64 bit depending upon your server.


Boolean : This type is used to store a boolean (true/ false) value.


Double : This type is used to store floating point values.


Min/ Max keys : This type is used to compare a value against the lowest and highest BSON elements.


Arrays : This type is used to store arrays or list or multiple values into one key.


Timestamp : ctimestamp. This can be handy for recording when a document has been modified or added.


Object : This datatype is used for embedded documents.


Null : This type is used to store a Null value.


Symbol : This datatype is used identically to a string however, it's generally reserved for languages that use a specific symbol type.


Date : This datatype is used to store the current date or time in UNIX time format. You can specify your own date time by creating object of Date and passing day, month, year into it.


Object ID : This datatype is used to store the document’s ID.


Binary data : This datatype is used to store binay data.


Code : This datatype is used to store javascript code into document.


Regular expression : This datatype is used to store regular expression


MongoDB - Query Document
find() Method
To query data from MongoDB collection, you need to use MongoDB's find() method.
>db.COLLECTION_NAME.find()
find() method will display all the documents in a non structured way.
pretty() Method
To display the results in a formatted way, you can use pretty() method.
>db.mycol.find().pretty()
 findOne() method
Apart from find() method there is findOne() method, that reruns only one document.


RDBMS Where Clause Equivalents in MongoDB
To query the document on the basis of some condition, you can use following operations
Operation
Syntax
Example
RDBMS Equivalent
Equality
{<key>:<value>}
db.mycol.find({"by":"tutorials point"}).pretty()
where by = 'tutorials point'
Less Than
{<key>:{$lt:<value>}}
db.mycol.find({"likes":{$lt:50}}).pretty()
where likes < 50
Less Than Equals
{<key>:{$lte:<value>}}
db.mycol.find({"likes":{$lte:50}}).pretty()
where likes <= 50
Greater Than
{<key>:{$gt:<value>}}
db.mycol.find({"likes":{$gt:50}}).pretty()
where likes > 50
Greater Than Equals
{<key>:{$gte:<value>}}
db.mycol.find({"likes":{$gte:50}}).pretty()
where likes >= 50
Not Equals
{<key>:{$ne:<value>}}
db.mycol.find({"likes":{$ne:50}}).pretty()
where likes != 50




AND in MongoDB


In the find() method if you pass multiple keys by separating them by ',' then MongoDB treats it AND condition.

>db.mycol.find({key1:value1, key2:value2}).pretty()
Below given example will show all the tutorials written by 'tutorials point' and whose title is 'MongoDB Overview'

>db.mycol.find({"by":"tutorials point","title": "MongoDB Overview"}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>
For the above given example equivalent where clause will be ' where by='tutorials point' AND title='MongoDB Overview' '. You can pass any number of key, value pairs in find clause.

OR in MongoDB


To query documents based on the OR condition, you need to use $or keyword. Basic syntax of OR is shown below:

>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()


Below given example will show all the tutorials written by 'tutorials point' or whose title is 'MongoDB Overview'

>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>

Using AND and OR together

Below given example will show the documents that have likes greater than 100 and whose title is either 'MongoDB Overview' or by is 'tutorials point'. Equivalent sql where clause is 'where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')'

>db.mycol.find("likes": {$gt:10}, $or: [{"by": "tutorials point"}, {"title": "MongoDB Overview"}] }).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>

MongoDB Update Document
MongoDB's update() and save() methods are used to update document into a collection. The update() method update values in the existing document while the save() method replaces the existing document with the document passed in save() method.
MongoDB Update() method
The update() method updates values in the existing document.
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)


Consider the mycol collectioin has following data.


{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}


By default mongodb will update only single document, to update multiple you need to set a paramter 'multi' to true.


>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}},{multi:true})


MongoDB Save() Method
The save() method replaces the existing document with the new document passed in save() method


>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
Following example will replace the document with the _id '5983548781331adf45ec7'
>db.mycol.save(
{
"_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point New Topic", "by":"Tutorials Point"
}
)
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"Tutorials Point New Topic", "by":"Tutorials Point"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}




MongoDB Delete Document



remove() Method
MongoDB's remove() method is used to remove document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag


deletion criteria : (Optional) deletion criteria according to documents will be removed.


justOne : (Optional) if set to true or 1, then remove only one document.
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)


Consider the student collectioin has following data.
db.student.find().pretty()
{
"_id" : ObjectId("54fbd3d82ca95514f09447fb"),
"sid" : "001",
"sname" : "satyanarayana",
"marks" : "33"
}
{
"_id" : ObjectId("54fbd40a2ca95514f09447fc"),
"sid" : "002",
"sname" : "sai",
"ramu" : "55"
}
{
"_id" : ObjectId("54fbd43e2ca95514f09447fd"),
"sid" : "003",
"sname" : "sai",
"marks" : "66"
>db.student.remove({‘sname’:’sai’})=====this will remove all records whose name is satya
If we want to remov only one record use the following
Remove only one
If there are multiple records and you want to delete only first record, then set justOne parameter in remove() method


>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)


>db.student.remove({‘sname’:’sai’},1)====this will remove only one document
Remove All documents
If you don't specify deletion criteria, then mongodb will delete whole documents from the collection. This is equivalent of SQL's truncate command.


>db.mycol.remove({})=======this will remove the all documents from collection
>db.mycol.find()

MongoDB Projection

In mongodb projection meaning is selecting only necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.


The find() Method
MongoDB's find() method, explained in MongoDB Query Document accepts second optional parameter that is list of fields that you want to retrieve. In MongoDB when you execute find() method, then it displays all fields of a document. To limit this you need to set list of fields with value 1 or 0. 1 is used to show the filed while 0 is used to hide the field.


>db.COLLECTION_NAME.find({},{KEY:1})


Following example will display the title of the document while quering the document.


>db.mycol.find({},{"title":1,_id:0})
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
{"title":"Tutorials Point Overview"}
>
Please note _id field is always displayed while executing find() method, if you don't want this field, then you need to set it as 0
MongoDB Limit Records
The Limit() Method
To limit the records in MongoDB, you need to use limit() method. limit() method accepts one number type argument, which is number of documents that you want to displayed.
Syntax:
>db.COLLECTION_NAME.find().limit(NUMBER)


Following example will display only 2 documents while quering the document.
>db.mycol.find({},{"title":1,_id:0}).limit(2)
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
>
If you don't specify number argument in limit() method then it will display all documents from the collection.


MongoDB Skip() Method
Apart from limit() method there is one more method skip() which also accepts number type argument and used to skip number of documents.
>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
Following example will only display only second document.
>db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL Overview"}
>
Please note default value in skip() method is 0
MongoDB Sort Documents
sort() Method
To sort documents in MongoDB, you need to use sort() method. sort() method accepts a document containing list offields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.
Basic syntax of sort() method is as follows
>db.COLLECTION_NAME.find().sort({KEY:1})
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})


Please note if you don't specify the sorting preference, then sort() method will display documents in ascending order.




MongoDB Indexing


Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every document of a collection to select those documents that match the query statement. This scan is highly inefficient and require the mongod to process a large volume of data.
Indexes are special data structures, that store a small portion of the data set in an easy to traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field as specified in index.
ensureIndex() Method
To create an index you need to use ensureIndex() method of mongodb.
Basic syntax of ensureIndex() method is as follows()
>db.COLLECTION_NAME.ensureIndex({KEY:1})
Here key is the name of filed on which you want to create index and 1 is for ascending order. To create index in descending order you need to use -1.


>db.mycol.ensureIndex({"title":1})
In ensureIndex() method you can pass multiple fields, to create index on multiple fields.
>db.mycol.ensureIndex({"title":1,"description":-1})
>
ensureIndex() method also accepts list of options (which are optional), whose list is given below:


MongoDB Aggregation
Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. In sql count(*) and with group by is an equivalent of mongodb aggregation.
aggregate() Method
For the aggregation in mongodb you should use aggregate() method.
Basic syntax of aggregate() method is as follows
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
In the collection you have the following data
MongoDB Create Backup
Dump MongoDB Data
To create backup of database in mongodb you should use mongodump command. This command will dump all data of your server into dump directory. There are many options available by which you can limit the amount of data or create backup of your remote server.
Basic syntax of mongodump command is as follows

>mongodump

Tuesday, May 5, 2015

Generating JavaDocumentation to our projects in Eclipse

This is the way to generate javadoc to our projects.

1 Go to project menu
2 select generate Javadoc
3 select project which you want to generate docs
4 select location where you want to store

Running Java main Programs using Maven Pom.xml


Add the following configuration we can run consloe java applications using Maven POM.xml

<build>
<plugins>
<plugin>
<artifactId>maven-plugin-plugin</artifactId>
<version>2.3</version>
<configuration>
<goalPrefix>clean</goalPrefix>
<goalPrefix>install</goalPrefix>
<goalPrefix>run</goalPrefix>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.hps.utility.main.DataUploadUtility</mainClass>
</configuration>
</plugin>

creating jar file in Eclipse




Saturday, September 6, 2014

Multithreading Interview Questions

Multithreading



Q1. What is Multitasking?
Ans. Executing several task simultaneously is called multitasking.

Q2. What is the difference between process-based and Thread-based Multitasking?
Ans.
Process-based multitasking:- Executing several task simultaneously where each task is a separate independent process such type of multitasking is called process based Multitasking. Example:-While typing a program in the editor we can listen MP3 audio songs. At the same time we download a file from the net.       all these task are executing simultaneously and each task is a separate independent program. hence it is process based multitasking. It is best suitable at operating system level.
Thread-based multitasking:- Executing several task simultaneously where each task is a separate independent part of the same program is called Thread-based multitasking. and every independent part is called a thread. This type of multitasking is best suitable at programmatic level.

Q3. What is Multithreading and explain its application areas? 
Ans. Executing several thread simultaneously where each thread is a separate independent part of the same program is called multithreading. Java language provides inbuilt support for multithreading by defining a reach library, classes and interfaces like Thread, ThreadGroup, Runnable etc. The main important application area of multithreading are video games implementation, animation development, multimedia graphics etc.

Q4.What is advantage of Multithreading?
Ans. The main advantage of multithreading is reduces response time and improves performance of the system.
Q5. When compared with C++ what is the advantage in java with respect to Multithreading?
Ans.Java language provides inbuilt support for multithreading by defining a reach library, classes and interfaces like Thread, ThreadGroup, Runnable etc. But in c++ there is no inbuilt support for multithreading.

Q6. In how many ways we can define a Thread? Among extending Thread and implementing Runnable which is recommended?
Ans. We can define a Thread in the following two ways:
1.      by extending Thread class or
2.      by implementing Runnable interface.
Among the two ways of defining a thread implementing Runnable mechanismis always recommended. In the first approach as our Thread class already extending Thread there is no chance of extending any other. Hence, we missing the key benefit of oops(inheritance properties).

Q7.  What is the difference between t.start() and t.run() method? 
Ans.       In the case of t.start() method, a new thread will be created which is responsible for the execution of run() method.
                But in the case of t.run() method no new thread will be created main thread executes run() method just like a normal method call.   
 

Q8.         Explain about Thread Scheduler?
Ans.    If multiple threads are waiting for getting the chance for executing then which thread will get chance first decided by Thread Scheduler. It is the part of JVM and its behavior is vendor dependent and we can’t expect exact output.Whenever the situation comes to multithreading the guarantee behavior is very- very low.

Q9. If we are not overriding run() method what will happened?
Ans.If we are not overriding run() method then Thread class run() method will executed which has empty implementation and hence we will not get any output.

Q10.Is overloading of run() method is possible?
Ans.Yes, we can overload run() method but Thread class start() method always invokes no-argument run() method only. The other run() method we have to call explicitly then only will be executed.

Q11.Is it possible to override start() method?
Ans. Yes it is possible. But not recommended.

Q12.If we are overriding start() method then what will happen?
Ans.  It we are overriding start() method then our own start() method will be executed just like a normal method call. In this case no new Thread will be created.

Q13. Explain life cycle of a Thread?
Ans.   Once we create a Thread object then the Thread is said to be in New/Born state once we call t.start() method now the Thread will be entered into ready/Runnable state that is Thread is ready to execute. If Thread Scheduler allocates CPU now the Thread will entered into the Running state and start execution of run() method. After completing run() method the Thread entered into Dead State.

Q14. What is the importance of Thread class start() method? 
Ans.    Start() method present in Thread class performing all low level joining formalities for the newly created thread like registering thread with Thread Scheduler etc and then start() method invoking run() method.As the start() method is doing all low level mandatory activities, Programmer has to concentrate only on run() method to define the job. Hence, start() method is a big assistant to the programmer.Without executing Thread class start() method there is no chance of starting a new Thread.

Q15. After starting a Thread if we trying to restart the same thread once again what will happen?
Ans.  After starting a Thread restarting of the same Thread once again is not allowed violation leads to Runtime Exception saying IllegalThreadStateException.
 

Q16. Explain Thread class constructors?
Ans.  There are eight constructors are available in Thread class:
1. Thread t=new Thread();          
 
2. Thread t=new Thread(Runnable r);    
 
3. Thread t=new Thread(String name);  
 
4.Thread t=new Thread(Runnable r, String name);          
 
5.Thread t=new Thread(ThreadGroup g, String name);  
 
6.Thread t=new Thread(ThreadGroup g, Runnable r);    
 
7.Thread t=new Thread(ThreadGroup g, Runnable r, String name);         
 
8.Thread t=new Thread(ThreadGroup g, Runnable r, String name, long stacksize);
Q17.  How to get and set name of a Thread?
Ans.   For every Thread in java there is a name. To set and get the name of a Thread we can use the following methods. All methods are final.
1.Public final void setName(String name); - To set the name of a Thread
2.Public final String getName(); - To get the name of a Thread.

Q18. What is the range of Thread priority in java?
Ans.   The valid range of a Thread priority is 1-10. (1 is least priority and 10 is highest priority)
.
Q19.  Who uses Thread priority?
Ans.   Thread Scheduler uses priorities while allocating CPU. The Thread which is having highest priority will get chance first for execution.

Q20.  What is the default priority of the Thread?
Ans.   The default priority only for the main thread is 5 but for all remaining threads default priority will be inheriting from parent to child. Whatever priority parent thread has the same will be inherited to the child thread.
Q21. Once we created a new Thread what about its priority?
Ans.  Whatever priority parent thread has the same will be inherited to the new child thread.

Q22.  How to get and set priority of a Thread?
Ans.    To get and set priority of a Thread, Thread class defines the following two methods:;
1.         Public final int getPriority();                                                                                                                                   
2.        Public final void setPriority(int priority);

Q23.   If we are trying to set priority of a Thread as 100 what will happen?
Ans.    If we are trying to set priority of a Thread as 100 then we will not get any compile time error but at the runtime we will get Runtime exception IllegalArgumentException. Because the valid range of the Thread priority is (1-10) only.

a Thread from executin by using the following methods:
1.     Yield()
2.     Join()
3.     Sleep()
Q27. What is yield() method? Explain its purpose?
Ans.   yield() method causes the current executing thread to pause execution and give the chance for waiting thread are same priority. If there is no waiting thread or all the remaining waiting thread have low priority then the same thread will get chance once again for execution. The Thread which is yielded when it will get chance once again for execution depends upon mercy of Thread scheduler.Public static native void yield();
                             
 
Q28.What is purpose of join() method?
Ans.  If a Thread wants to wait until some other Thread completion then we should go for join() method.
 
         Example: if a Thread t1 execute t2.join() ; then t1 will entered into waiting state until t2 Thread completion.
Q29. Is join() method is overloaded?
Ans.       Yes join() method is overloaded method.
                Public final void join() throws InterruptedException
                                By using this method thread will wait up to another thread completion .
                Public final void join(long ms) throws InterruptedException
By using this method thread will wail upto sometime what we are passing as a argument in millisecond 
Public final void join(long ms, int ns)throws InterruptedException
By using this method thread will wait up to sometime what we are passing as a argument in millisecond and nanosecond.

Q30 What is the purpose of sleep() method?
Ans.  If a Thread don’t want to perform any operation for a particular amount of time then we should go for sleep() method.Whenever we are using sleep() method compulsory we should handle InterruptedException either by using try-catch or by using throws keyword otherwise we will get compile time error.


Q31. What is synchronized keyword? Explain its advantages and disadvantages.
Ans.       Synchronized keyword is applicable for method and blocks only. We can’t use for variables and classes.
                If a method declared as a synchronized then at a time only one Thread is allow to execute that method on the given object.
                The main advantages of synchronized keyword are, we can prevent data inconsistency problems and we can provide Threadsafty.
                But the main limitation of synchronized keyword is it increases waiting time of Threads and effect performance of the system. Hence if there is no specific requirement it is not recommended to use synchronized keyword.

Q32.Where we can use synchronized keyword?
Ans. Synchronization concept is applicable whenever multiple Threads are operating on the same object simultaneously. But whenever multiple Threads are operating on different objects then there is no impact of synchronization.

Q33. What is object lock? Explain when it is required?
Ans.   Every object in java has a unique lock whenever we are using synchronization concept then only lock concept will coming to the picture.
If a Thread wants to execute a synchronized method first it has to get the lock of the object. Once a Thread got the lock then it is allow to execute any synchronized method on that object. After completing synchronized method execution Thread releases the lock automatically.While a Thread executing synchronized method on the given object the remaining Threads are not allow to execute any synchronized method on that object simultaneously. But remaining Threads are allow to execute any non-synchronized method simultaneously. (Lock concept is implemented based on object but not based on method.)

Q34.What is the class level lock? Explain its purpose.
Ans. Every class in java has a unique lock if a Thread wants to execute static synchronized method that Thread has to get class level lock once a Thread got class level lock then only it is allow to execute static synchronized method.              
 
While a Thread executing any static synchronized method then remaining Threads are not allow to execute any static synchronized method of the same class simultaneously. But the remaining Threads are allow to execute the following method simultaneously:
1.     Any static non-synchronized method.
2.     Synchronized instance methods
3.     Non-synchronized instance method.
                There is no relationship between object lock and class level lock, both are independent.
                               
 
Q35. While a thread executing any synchronized method on the given object is it possible to execute remaining synchronized method of the same object simultaneously by any other thread?
Ans.       No, it is no possible.

Q36. What is the difference between synchronized method and static synchronized method?
Ans.   If a Thread wants to execute a
 synchronized method first it has to get the lock of the object. Once a Thread got the lock then it is allow to execute any synchronized method on that object.If a Thread wants to execute static synchronized method that Thread has to get class level lock once a Thread got class level lock then only it is allow to execute static synchronized method.

Q37. What is the advantage of synchronized block over synchronized method?
Ans.   If very few lines of the code required synchronization then declaring entire method as the synchronized is not recommended. We have to declare those few lines of the code inside synchronized block. This approach reduces waiting time of the Thread and improves performance of the system.

Q38.  What is synchronized statement?
Ans.   The Statement which is inside the synchronized area (synchronized method or synchronized block) is called synchronized statement.

Q39.  How we can declare synchronized block to get class level lock?
Ans.   To get the class level lock we can declare synchronized block as follows:
           synchronized(Display.class)
             {
              }

Q40.   How two thread will communicate with each other?
Ans.    Two Threads will communicate with each other by using wait(), notify(), notifyAll() methods.
Q41.wait(), notify(), notifyAll() method can available in which class?
Ans. These methods are defined in Object class.

Q42.Why wait(), notify(), notifyAll() method defines in object class instead of Thread class?
Ans. These methods are defined in Object class but not in Thread because Threads are calling this method on the shared object.

Q43.If a waiting thread got notification then it will entered into which state?
Ans. It will entered into another waiting state to get lock.

Q44.In which method threads can release the lock?
Ans. Once a Thread calls wait() method it immediately releases the lock of that object and then entered into waiting state similarly after calling notify() method Thread releases the lock but may not immediately. Except these three methods( wait(), notify(), notifyAll() ) method Thread never releases the lock anywhere else.
 
Q45. Explain wait(), notify(), notifyAll() method uses.
Ans.  Two Threads will communicate with each other by using wait(), notify() or notifyAll() methods.
         These methods are defined in Object class but not in Thread because Threads are calling this method.

Q46. What is the difference between notify() and notifyAll()?
Ans.  To give notification to the single waiting Thread. We use notify() method and to give
notification to all waiting thread we use notifyAll() method.
Q47. Once a Thread got the notification then which waiting thread will get chance?
Ans.   It is depends on the Thread Scheduler.

Q48.   How a thread can interrupt another thread?
Ans.  A Thread can interrupt another Thread by using interrupt() method.
Q49. What is DeadLock? Is it possible to resolve DeadLock situation?
Ans.   If two Threads are waiting for each other forever such type of situation is called DeadLock.
          For the DeadLock, there are no resolution techniques but prevention techniques are available.  
                            
Q50. Which keyword causes DeadLock situation?
Ans.  Synchronized keyword is the thing to causes of DeadLock. If we are not using properly synchronized keyword the program will entered into DeadLock situation. 


Q51.  How we can stop a thread explacitly?
Ans.  Thread class defines stop() method by using this method we can stop a Thread. But it is deprecated. And hence not recommended to use.

Q52.   Explain about suspend() and resume() method?
Ans.   A Thread can suspend another Thread by using suspend() method.
A Thread can resume a suspended Thread by using resume() method.

Q53.What is Starvation()? And Explain the difference between Deadlock and Starvation?
Ans. A long waiting Thread is said to be in starvation (because of least priority) but after certain time defiantly it will get the chance for execution. But in the case of Deadlock two Threads will wait for each other forever. It will never get the chance for execution.
Q54. What is race condition?
Ans.  Multiple Threads are accessing simultaneously and causing data inconsistency problem is called race condition, we can resolve this by using synchronized keyword.

Q55. What is Daemon Thread? And give an example?
Ans.  The Threads which are running in the background are called Daemon Thread.
                Example: Garbage collector.
Q56. What is the purpose of a Daemon Thread?
Ans.  The main purpose of Daemon Threads is to provide support for non-daemon Threads.

Q57.  How we can check Daemon nature of a Thread?
Ans.   We can check Daemon nature of a Thread by using isDaemon() method.

Q58.  Is it possible to change a Daemon nature of a Thread?
Ans.  Yes, we can change Daemon nature of a Thread by using setDaemon() method.

Q59. Is main thread is Daemon or non-daemon?
Ans.  By default main thread is always non-daemon nature.

Q60. Once we created a new thread is it daemon or non-daemon.
Ans.   Once we created a new Thread, The Daemon nature will be inheriting from parent to child. If the parent is Daemon the child is also Daemon and if the parent is non-daemon then child is also non-daemon.

Q61. After starting a thread is it possible to change Daemon nature?
Ans.  We can change the Daemon nature before starting the Thread only. Once Thread started we are not allow to change Daemon nature otherwise we will get RuntimeException sying IllegalThreadStateException.

Q62. When the Daemon thread will be terminated?
Ans.  Once last non-daemon Thread terminates automatically every Daemon Thread will be terminated.

Q63. What is green Thread?
Ans.   A green thread refers to a mode of operation for the Java Virtual Machine (JVM) in which all code is executed in a single operating system thread. If the Java program has any concurrent threads, the JVM manages multi-threading internally rather than using other operating system threads.
There is a significant processing overhead for the JVM to keep track of thread states and swap between them, so green thread mode has been deprecated and removed from more recent Java implementations. 

Q64.Explain about Thread group?
Ans. Every Java thread is a member of a thread group. Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually. For example, you can start or suspend all the threads within a group with a single method call. Java thread groups are implemented by the ThreadGroup api class in the java.lang package.

Q65.What is the Thread Local?
Ans.  It's a way for each thread in multi-threaded code to keep its own copy of an instance variable. Generally, instance variable are shared between all threads that use an object; ThreadLocal  is a way for each thread to keep its own copy of such a variable. The purpose might be that each thread keeps different data in that variable, or that the developer wants to avoid the overhead of synchronizing access to it. 
Q66. In your previous project where you used multithreading concept?