Search This Blog
Showing posts with label swing. Show all posts
Showing posts with label swing. Show all posts
Tuesday, 10 June 2014
Saturday, 12 April 2014
How Volatile in Java works ? Example of volatile keyword in Java
Any way Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in int or boolean variable you can declare them as volatile variable. From Java 5 along with major changes like Autoboxing, Enum, Genericsand Variable arguments , Java introduces some change in Java Memory Model (JMM), Which guarantees visibility of changes made by one thread to another also as "happens-before" which solves the problem of memory writes that happen in one thread can "leak through" and be seen by another thread. Java volatile keyword cannot be used with method or class and it can only be used with variable. Java volatilekeyword also guarantees visibility and ordering , after Java 5 write to any volatile variable happens before any read into volatile variable. By the way use of volatile keyword also prevents compiler or JVM from reordering of code or moving away them from synchronization barrier.
Example of volatile keyword in Java:
To Understand example of volatile keyword in java let’s go back to Singleton pattern in Java and see double checked locking in Singleton with Volatile and without volatile keyword in java.
/**
* Java program to demonstrate where to use Volatile keyword in Java.
* In this example Singleton Instance is declared as volatile variable to ensure
* every thread see updated value for _instance.
*
* @author Javin Paul
*/
public class Singleton{
private static volatile Singleton _instance; //volatile variable
public static Singleton getInstance(){
if(_instance == null){
synchronized(Singleton.class){
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
* Java program to demonstrate where to use Volatile keyword in Java.
* In this example Singleton Instance is declared as volatile variable to ensure
* every thread see updated value for _instance.
*
* @author Javin Paul
*/
public class Singleton{
private static volatile Singleton _instance; //volatile variable
public static Singleton getInstance(){
if(_instance == null){
synchronized(Singleton.class){
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
If you look at the code carefully you will be able to figure out:
1) We are only creating instance one time
2) We are creating instance lazily at the time of first request comes.
If we do not make _instance variable volatile then Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe its still null.
Why because reader threads are not doing any locking and until writer thread comes out of synchronized block, memory will not be synchronized and value of _instance will not be updated in main memory. With Volatile keyword in Java this is handled by Java himself and such updates will be visible by all reader threads.
Let’s see another example of volatile keyword in Java:
most of the time while writing game we use a variable bExist to check whether user has pressed exit button or not, value of this variable is updated in event thread and checked in game thread , So if we don't use volatile keyword with this variable , Game Thread might miss update from event handler thread if its not synchronized in java already. volatile keyword in java guarantees that value of volatile variable will always be read from main memory and "happens-before" relationship in Java Memory model will ensure that content of memory will be communicated to different threads.
private boolean bExit;
while(!bExit) {
checkUserPosition();
updateUserPosition();
}
while(!bExit) {
checkUserPosition();
updateUserPosition();
}
In this code example One Thread (Game Thread) can cache the value of "bExit" instead of getting it from main memory every time and if in between any other thread (Event handler Thread) changes the value; it would not be visible to this thread. Making boolean variable "bExit" as volatile in java ensures this will not happen.
When to use Volatile variable in Java
1) You can use Volatile variable if you want to read and write long and double variable atomically. long and double both are 64 bit data type and by default writing of long and double is not atomic and platform dependence. Many platform perform write in long and double variable 2 step, writing 32 bit in each step, due to this its possible for a Thread to see 32 bit from two different write. You can avoid this issue by making long and double variable volatile in Java.
2) Volatile variable can be used as an alternative way of achieving synchronization in Java in some cases, like Visibility. with volatile variable its guaranteed that all reader thread will see updated value of volatile variable once write operation completed, without volatile keyword different reader thread may see different values.
3) volatile variable can be used to inform compiler that a particular field is subject to be accessed by multiple threads, which will prevent compiler from doing any reordering or any kind of optimization which is not desirable in multi-threaded environment. Without volatile variable compiler can re-order code, free to cache value of volatile variable instead of always reading from main memory. like following example withoutvolatile variable may result in infinite loop
private boolean isActive = thread;
public void printMessage(){
while(isActive){
System.out.println("Thread is Active");
}
}
public void printMessage(){
while(isActive){
System.out.println("Thread is Active");
}
}
without volatile modifier its not guaranteed that one Thread see the updated value of isActive from other thread. compiler is also free to cache value of isActive instead of reading it from main memory in every iteration. By making isActive a volatile variable you avoid these issue.
4) Another place where volatile variable can be used is to fixing double checked locking in Singleton pattern. As we discussed in Why should you use Enum as Singleton that double checked locking was broken in Java 1.4 environment.
Important points on Volatile keyword in Java
1. volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal.
2. volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache.
3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).
4. Using Volatile keyword in Java on variables reduces the risk of memory consistency errors, because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.
5. From Java 5 changes to a volatile variable are always visible to other threads. What’s more it also means that when a thread reads a volatile variable in java, it sees not just the latest change to the volatile variable but also the side effects of the code that led up the change.
6. Reads and writes are atomic for reference variables are for most primitive variables (all types except long and double) even without use of volatile keyword in Java.
7. An access to a volatile variable in Java never has chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait for any lock.
8. Java volatile variable that is an object reference may be null.
9. Java volatile keyword doesn't means atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.
10. If a variable is not shared between multiple threads no need to use volatile keyword with that variable.
Friday, 11 April 2014
Difference between InvokeLater and InvokeAndWait in Java Swing
Why do we need InvokeLater method in Swing?
As we all know java swing is not threadsafe , you can not update swing component like JButton, JLable , JTable or JTree from any thread , they all needs to be updated from just one thread and we call it Event Dispatcher thread or EDT in short. Event Dispatcher thread is used to render graphics for java swing component and also process all events corresponding to key press, mouse click or any action. So if you want to update a particular swing component suppose label of a JButton from Yes to No you need to do this in Event Dispatcher thread and for doing this you need InvokeLater. invokeLater is used to perform any task asynchronously on AWT Event Dispatcher thread.What is invokeLater in Java Swing
Invokelater is a method in java on swing package and belongs to swingutilities class. Invokelater is used by java swing developer to update or perform any task on Event dispatcher thread asynchronously.invokeLater has been added into Java API from swing extension and it’s belong to SwingUtilities class.
How does invokeLater works in Java Swing
If you see the signature of invokeLater method you will find that invokeLater takes a Runnable object and queues it to be processed by EventDispatcher thread. EDT thread will process this request only after sorting out all AWT pending events or requests. Even if invokeLater is called directly form Event dispatches thread processing of Runnable task still be done only after processing all pending AWT Events. An important point to note is that in case if run method of Runnable task throw any exception then AWT Event dispatcher thread will unwind and not the current thread.
Why do we need InvokeAndWait method in Swing
As we know that Swing is not thread-safe and we can not update the Swing component or GUI from any thread. If you try to update GUI form any thread you will get unexpected result or exception, it could be your GUI might not be visible or simply disappered. Only method which is thread-safe in swing is repaint() and revalidate(). On the other hand InvokeAndWait allows us to update the GUI from EDT thread synchronously. InvokeAndWait method also belongs to swingUtility class like invokeLater.
How does InvokeAndWait works in Java Swing
If you look at the signature of invokeAndWait method you will see that it takes a Runnable object and run method of that Runnable is executed synchronously on EDT. This is a blocking call and wait until all pending AWT events gets processed and run() method completes. Its a preferred way of updating GUI form application thread.
Important point to note is that it should not be called from EventDispatcher thread unlike invokeLater; it’s an error because it will result in guaranteed deadlock. because if you cal invokeAndWait from EDT thread it will be an AWT event and caller of invokeAndWait will wait for EDT thread to complete and EDT will wait caller thread to be completed so they will be locked in deadlock. Its also important to remember that if run() mehtod of Runnable object throw exception then its caught in AWT EDT thread and rethrown as InvocationTargetException on caller thread.
Example of InvokeLater in Java Swing
Here is an example of invokeLater() in Swing which will demonstrate that in case of invokeLater application thread doesn’t block.
Runnable pickHighBetaStock = new Runnable() {
public void run() {
System.out.println("High beta Stock picked by " + Thread.currentThread());
}
};
SwingUtilities.invokeLater(pickHighBetaStock);
System.out.println("This might well be displayed before the other message. if Event-dispatcher thread is busy");
Example of using InvokeAndWait in Java Swing
In this example of InvokeAndWait we will see that Application thread will block until Runnable object passed to EDT has been executed.
final Runnable pennyStockPicker = new Runnable() {
public void run() {
System.out.println("pick penny Stock on " + Thread.currentThread());
}
};
Thread stockPicker = new Thread() {
public void run() {
try {
SwingUtilities.invokeAndWait(pennyStockPicker);
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("This will finish after pennyStockPicker thread because InvokeAndWait is block call" + Thread.currentThread());
}
};
stockPicker.start();
Difference on InvokeLater vs InvokeAndWait in Swing
Swingutilies provides us two methods for performing any task in Event dispatcher thread. Now let's see what the difference between invokeLater and InvokeAndWait is and when to use invokeLater.
1) InvokeLater is used to perform task asynchronously in AWT Event dispatcher thread while InvokeAndWait is used to perform task synchronously.
2) InvokeLater is non blocking call while InvokeAndWait will block until task is completed.
3) If run method of Runnable traget throws an Exception then in case of invokeLater EDT threads unwinds while in case of invokeAndWait exception is caught and rethrown as InvocationTargetException.
4) InvokeLater can be safely called from Event Dispatcher thread while if you call invokeAndWait from EDT thread you will get an error because as per java documentation of invokeAndWait it clearly says that "this request will be processed only after all pending events" and if you call this from EDT this will become one of pending event so its a deadlock because caller of InvokeAndWait is waing for completion of invokeAndWait while EDT is waiting for caller of InvokeAndWait.
5) InvokeLater is more flexible in terms of user interaction because it just adds the task in queue and allow user to interact with system while invokeAndWait is preffered way to update the GUI from application thread.
In Summary we can just say that since Swing is not thread-safe and we cannot update different Swing GUI components on any thread other-than Event dispatcher Thread we need to use InvokeAndWait or InvokeLater to schedule any Runnable task for AWT Event dispatcher Thread. InvokeAndWait is synchronous and blocking call and wait until submitted Runnable completes while InvokeLater is asynchronous and non-blocking it will just submit task and exit."
That’s all on InvokeAndWait() and InvokeLater() method of SwingUtilities class. They are very important while doing GUI programming on Swing as well as this is very popular interview questions which I have discussed on my latest post on swing interview questions asked in Investment bank
Saturday, 15 March 2014
Assertion In Java
Assertion includes a Boolean expression. If the Boolean expression evaluates to false AssertionError is thrown. Assertion helps a programmer to debug the code effectively.
Assertion code is removed when the program is deployed. Below is a code snippet which checks if inventory object is null.
Inventory objInv = null;
// ...
// Get your inventory object reference here
// ...
// Use assert to check if the object is null
// by any chance
assert objInv != null;
Assertion code is removed when the program is deployed. Below is a code snippet which checks if inventory object is null.
Inventory objInv = null;
// ...
// Get your inventory object reference here
// ...
// Use assert to check if the object is null
// by any chance
assert objInv != null;
Difference between Abstract class and Interface
Difference between Abstract class and Interface is as follows:-
√ Abstract class can only be inherited while interfaces can not be it has to be implemented.
√ Interface cannot implement any methods, whereas an abstract class can have implementation.
√ Class can implement many interfaces but can have only one super class.
√ Interface is not part of the class hierarchy while Abstract class comes in through inheritance.
√ Unrelated classes can implement the same interface.
√ Abstract class can only be inherited while interfaces can not be it has to be implemented.
√ Interface cannot implement any methods, whereas an abstract class can have implementation.
√ Class can implement many interfaces but can have only one super class.
√ Interface is not part of the class hierarchy while Abstract class comes in through inheritance.
√ Unrelated classes can implement the same interface.
Wednesday, 29 January 2014
OOPS : Abstraction, Encapsulation, Inheritance, Polymorphism with Real Life Example
OOPS : Abstraction, Encapsulation, Inheritance, Polymorphism
OOPS Features
* The object oriented programming (OOP) is a programming model
where Programs are organized around object and data rather than
action and logic.
* OOP allow decomposition of a problem into a number of entities called
Object and then builds data and function around these objects.
where Programs are organized around object and data rather than
action and logic.
* OOP allow decomposition of a problem into a number of entities called
Object and then builds data and function around these objects.
- The Program is divided into number of small units called Object. The data and function are build around these objects.
- The data of the objects can be accessed only by the functions associated with that object.
- The functions of one object can access the functions of other object.
OOP has the following important features.
Class:
A class is the core of any modern Object Oriented Programming language such as C#.
In OOP languages it is must to create a class for representing data.
Class is a blueprint of an object that contains variables for storing data and functions to performing operations on these data.
Class will not occupy any memory space and hence it is only logical
representation of data.
To create a class, you simply use the keyword "class" followed by the class name:
class Employee
{
}
Object:
Objects are the basic run-time entities in an object oriented system.They may represent a person,a place or any item that the program has to handle.
"Object is a Software bundle of related variable and methods. "
Objects are the basic run-time entities in an object oriented system.They may represent a person,a place or any item that the program has to handle.
"Object is a Software bundle of related variable and methods. "
“Object is an instance of a class”
Class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, which is called as an object.
When an object is created by using the keyword new, then memory will be allocated for the class in heap memory area, which is called as an instance and its starting address will be stored in the object in stack memory area.
When an object is created without the keyword new, then memory will not be allocated in heap I.e. instance will not be created and object in the stack contains the value null.
When an object contains null, then it is not possible to access the members of the class using that object.
class Employee
{
}
Syntax to create an object of class Employee:-
Employee objEmp = new Employee();
All the programming languages supporting object oriented Programming will be supporting these three main concepts:
- Encapsulation
- Inheritance
- Polymorphism
Abstraction:
Abstraction is "To represent the essential feature without representing the back ground details."
Abstraction lets you focus on what the object does instead of how it does it.
Abstraction provides you a generalized view of your classes or object by providing relevant information.
Abstraction is the process of hiding the working style of an object, and showing the information of an object in understandable manner.
Real world Example of Abstraction: -
Suppose you have an object Mobile Phone.
Suppose you have 3 mobile phones as following:-
Nokia 1400 (Features:- Calling, SMS)
Nokia 2700 (Features:- Calling, SMS, FM Radio, MP3, Camera)
Black Berry (Features:-Calling, SMS, FM Radio, MP3, Camera, Video Recording, Reading E-mails)
Abstract information (Necessary and Common Information) for the object "Mobile Phone" is make a call to any number and can send SMS."
so that, for mobile phone object you will have abstract class like following:-
abstract class MobilePhone
{
public void Calling();
public void SendSMS();
}
public class Nokia1400 : MobilePhone
{
}
public class Nokia2700 : MobilePhone
{
public void FMRadio();
public void MP3();
public void Camera();
}
public class BlackBerry : MobilePhone
{
public void FMRadio();
public void MP3();
public void Camera();
public void Recording();
public void ReadAndSendEmails();
}
Abstraction means putting all the variables and methods in a class which are necessary.
For example: - Abstract class and abstract method.
Abstraction is the common thing.
example:
If somebody in your collage tell you to fill application form, you will fill your details like name, address, data of birth, which semester, percentage you have got etc.
If some doctor gives you an application to fill the details, you will fill the details like name, address, date of birth, blood group, height and weight.
See in the above example what is the common thing?
Age, name, address so you can create the class which consist of common thing that is called abstract class.
That class is not complete and it can inherit by other class.
Encapsulation:
Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.
Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object.
Encapsulation is like your bag in which you can keep your pen, book etc. It means this is the property of encapsulating members and functions.
class Bag
{
book;
pen;
ReadBook();
}
Encapsulation means hiding the internal details of an object, i.e. how an object does something.
Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is implemented.
Encapsulation is a technique used to protect the information in an object from the other object.
Hide the data for security such as making the variables as private, and expose the property to access the private data which would be public.
So, when you access the property you can validate the data and set it.
Example:
class Demo
{
private int _mark;
public int Mark
{
get { return _mark; }
set { if (_mark > 0) _mark = value; else _mark = 0; }
}
}
Real world Example of Encapsulation:-
Let's take example of Mobile Phone and Mobile Phone Manufacturer
Suppose you are a Mobile Phone Manufacturer and you designed and developed a Mobile Phone design(class), now by using machinery you are manufacturing a Mobile Phone(object) for selling, when you sell your Mobile Phone the user only learn how to use the Mobile Phone but not that how this Mobile Phone works.
This means that you are creating the class with function and by making object (capsule) of it you are making availability of the functionality of you class by that object and without the interference in the original class.
Example-2:
TV operation
It is encapsulated with cover and we can operate with remote and no need to open TV and change the channel.
Here everything is in private except remote so that anyone can access not to operate and change the things in TV.
Inheritance:
When a class acquire the property of another class is known as inheritance.
Inheritance is process of object reusability.
For example, A Child acquire property of Parents.
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("Parent Constructor.");
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class ChildClass : ParentClass
{
public ChildClass()
{
Console.WriteLine("Child Constructor.");
}
public static void Main()
{
ChildClass child = new ChildClass();
child.print();
}
}
Output:
Parent Constructor.
Child Constructor.
I'm a Parent Class.
Child Constructor.
I'm a Parent Class.
Polymorphism:
Polymorphism means one name many forms.
One function behaves different forms.
In other words, "Many forms of a single object is called Polymorphism."
Real World Example of Polymorphism:
Example-1:
A Teacher behaves to student.
A Teacher behaves to his/her seniors.
Here teacher is an object but attitude is different in different situation.
Example-2:
Person behaves SON in house at the same time that person behaves EMPLOYEE in office.
Example-3:
Your mobile phone, one name but many forms
- As phone
- As camera
- As mp3 player
- As radio
For Video Tutorials you can visit this Link:
Thank you....
Labels:
.net,
Abstraction,
Abstraction real world example,
advanced java,
Class real,
Classes,
Encapsulation,
Inheritance,
JAVA,
Object,
oops,
Polymorphism,
real life,
Structure,
swing,
with Real Life Example
Subscribe to:
Posts (Atom)