Pages

Label

Tampilkan postingan dengan label java. Tampilkan semua postingan
Tampilkan postingan dengan label java. Tampilkan semua postingan

Rabu, 30 Januari 2019

wait(), notify() and notifyAll() in Java



Hello Guys !!! Hope You all are doing well.
Today I am going to discuss one of the most import concept of java Thread.
wait(), notify() and notifyAll() methods are quite obvious because they are the one of the three methods of total 9 methods from java.lang.Object. I am sharing here some practical tips and points about wait(), notify() and notifyAll() in Java and its uses in java program.

1. wait, notify and notifyAll are related to threads they are not defined in java.lang.Thread class, instead they are defined in the Object class. why? as per my understanding there are three reason :-


(A) Wait and notify is not just normal methods or synchronization utility,They are communication mechanism between two threads in Java. So An Object class is correct place to make them available for every object.

(B) Locks are made available as per Object basis, that's why wait and notify is declared in Object class rather then Thread class.

(C) As per Java design, the thread can not be specified, it is always the current thread running the code. However, we can specify the monitor (object). So it is a good design, if we could make any other thread to wait on a desired monitor.

2. We must call the wait(), notify() and notifyAll() methods from a synchronized context in Java i.e. inside synchronized method or a synchronized block.
why is this restriction??? Explanation:-

(A) The thread must hold the lock on the object it is going to call the wait() or notify() method and that is acquired when it enter into a synchronized context.
If you call it without holding a lock then they will throw IllegalMonitorStateException in Java.

(B) To avoid any potential race condition between wait() and notify() method.

3. The best approach to call wait() method from inside a loop, don't call with an if block because a thread can occasionally or irregularly awake from the wait state without being notified by another party. So in that case, this could result in a bug.
example :-

synchronized (sharedObject) {

while (condition) {

sharedObject.wait();

}

// do something

}



4. When a thread calls the wait() method in Java, it goes to the wait state by releasing the lock, which is later acquired by the other thread who can notify this thread. Here is a nice diagram of how state transition of a thread happens in Java:
Inline image 1

5. A thread waiting due to wait() method call, then it can wake up either by calling notify() or notifyAll() method on the same object or due to interruption.

6. Difference between notify() and notifyAll() is that in case of notify() only one of the waiting thread gets a notification but in case of notifyAll() all thread get notification.

So far, we learned few basic things for wait, notify and notifyAll (which you probably already knew). Let’s write a small java program.

In this program, we will solve producer consumer problem using wait() and notify() methods.
To keep program simple, we will involve only one producer and one consumer thread.
Other features of the program are :

  1. Producer thread produce a new resource in every 1 second and put it in ‘taskQueue’.
  2. Consumer thread takes 1 seconds to process consumed resource from ‘taskQueue’.
  3. Max capacity of taskQueue is 7 i.e. maximum 7 resources can exist inside ‘taskQueue’ at any given time.
  4. Both threads run infinitely.

You can download source code from my github account

ProducerThread.java file add task in TaskQueue . Below is the full code :- 

packagecom.sks.softsolution.example;

importjava.util.List;

publicclassProducerThread implementsRunnable {

privatefinalList<Integer> taskQueue;
privatefinalintMAX_CAPACITY;
publicProducerThread(List<Integer> sharedQueue, intsize)
{
this.taskQueue= sharedQueue;
this.MAX_CAPACITY= size;
}
@Override
publicvoidrun() {
intcounter= 0;
while(true)
{
try
{
ProduceTask(counter++);
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
}
privatevoidProduceTask(inti) throwsInterruptedException
{
synchronized(taskQueue)
{
while(taskQueue.size() == MAX_CAPACITY)
{
System.out.println("Queue is full "+ Thread.currentThread().getName() + " is waiting , size: "+ taskQueue.size());
taskQueue.wait();//calling wait on taskQueue lock
}
Thread.sleep(1000);
taskQueue.add(i);
System.out.println("Produced: " + i);
taskQueue.notifyAll();
}
}
}


ConsumerThread.java is consuming task produced by Producer.java Below is the full code:-
packagecom.sks.softsolution.example;

importjava.util.List;

publicclassConsumerThread implementsRunnable
{
privatefinalList<Integer> taskQueue;
publicConsumerThread(List<Integer> sharedQueue)
{
this.taskQueue= sharedQueue;
}
@Override
publicvoidrun()
{
while(true)
{
try
{
consumeTask();
} catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
}
privatevoidconsumeTask() throwsInterruptedException
{
synchronized(taskQueue)
{
while(taskQueue.isEmpty())
{
System.out.println("Queue is empty "+ Thread.currentThread().getName() + " is waiting , size: "+ taskQueue.size());
taskQueue.wait();
}
Thread.sleep(1000);
inti= (Integer) taskQueue.remove(0);
System.out.println("Consumed: " + i);
taskQueue.notifyAll();
}
}
}
Now finally we have to start producer and consumer thread
packagecom.sks.softsolution.example;

importjava.util.ArrayList;
importjava.util.List;

publicclassProducerConsumerExampleWithWaitAndNotify {
publicstaticvoidmain(String[] args) {
List<Integer> taskQueue= newArrayList<Integer>();
intMAX_CAPACITY= 7;
Thread tProducer= newThread(newProducerThread(taskQueue, MAX_CAPACITY), "Producer");
Thread tConsumer= newThread(newConsumerThread(taskQueue), "Consumer");
tProducer.start();
tConsumer.start();
}

}
Output of this program 
Queue is empty Consumer is waiting , size: 0
Produced: 0
Produced: 1
Produced: 2
Produced: 3
Produced: 4
Produced: 5
Produced: 6
Queue is full Producer is waiting , size: 7
Consumed: 0
Consumed: 1
Consumed: 2
Consumed: 3
Consumed: 4
Consumed: 5
Consumed: 6
Queue is empty Consumer is waiting , size: 0
Produced: 7
Produced: 8
Produced: 9
Produced: 10
Produced: 11
Produced: 12
Produced: 13
Queue is full Producer is waiting , size: 7
Consumed: 7
Consumed: 8
Please provide your valuable feedback in comment section. it will help me to do my best.
Happy Coding!!!.....

Selasa, 29 Januari 2019

Install and Use Multiple version of JDK on Ubuntu

Hello Guys!!! hope you all are doing well!!!
Today a quick  and short discussion for installing and using multiple JDK on Ubuntu(Linux) System.

As a Android system developer (generally AOSP framework) we need different Open JDK for different Android platform. As for example, Let say if we want to build Android KK then we have to use JDK 1.5 or 1.6, for Android M we need JDK 1.7, for Android N we need Open JDK 1.8.

first let us install the two different versions of JDKs on our system.

#type the command on the terminal to install JDK 9:
 $ sudo apt-get install openjdk-9-jdk
you may ask to enter password.so enter password to finish the installation, after installation gets complete,you can confirm it by typing in the terminal:
$ java -version 
it will show the version of JDK which you just installed.
now we have to install other version of JDK. # Install JDK 8 by command in terminal:
$ sudo apt-get install openjdk-8-jdk 
now we have both JDK 9 and JDK 8 installed on our system.

if you enter java -version on terminal,it will give only default version of JDK not the both. so to check both installed versions of JDK,enter following command on terminal:
$ update-java-alternatives --list
it will give you both versions of JDK like this: 
now if you want to switch from the default version of JDK to your desired version, enter the
following command on terminal:
$ sudo update-alternatives --config java
after entering the command you will get the list indicating the current JDK version by prefixing * on it. Here below in our case it is JDK 9 which is set by default.

Now we can enter the number of the JDK version which you want to switch to or just press enter key if you want to keep the current one.
That's all now you can switch to any installed version of JDK whenever you want.

For installing Java 6 (JDK/JRE 6)
$ sudo add-apt-repository ppa:webupd8team/java
$ sudo apt-get update
$ sudo apt-get install oracle-java6-installer
After successfully installing oracle java using above step verify installed version using following command.
 java -version or javac -version 
Webupd8team is providing a package to set environment variables, Install this package using following command.
$ sudo apt-get install oracle-java6-set-default
Same way you can install Java 7 , just run the following command 
sudo apt-get install oracle-java7-installer
Second approach
Download the .deb packages for 64-bit architecture from archive.ubuntu.com and install this JDK package by using Run dpkg for each of the .deb files you downloaded.
$ sudo dpkg -i {downloaded.deb file}
To fix missing dependencies:
$ sudo apt-get -f install



Happy Coding!!!
 
[tutup]