Friday, 13 July 2012
Tuesday, 3 July 2012
If a synchronized method calls another non-synchronized method, is there a lock on the non-synchronized method?
If you are in a synchronized method then calls to other methods that are also synchronized are locked however calls to non-synchronized are not locked -- any method can call them at the same time.
Other calls to synchronized methods are locked. But non-synchronized methods are not locked.
Also, remember that if the method is static then the lock is on the Class object in the ClassLoader.
If the method is an instance method then the lock is on the instance Object.
public synchronized void synchronizedMethod() { ... nonSynchronizedMethod(); ... } /* any method can call this method even if the synchronizedMethod() method has been called and the lock has been acquired*/ public void nonSynchronizedMethod() { ... }Everything in the synchronized method have a lock on it (including calls to other synchronized methods).
Other calls to synchronized methods are locked. But non-synchronized methods are not locked.
Also, remember that if the method is static then the lock is on the Class object in the ClassLoader.
If the method is an instance method then the lock is on the instance Object.
// this locks on the Class object in the ClassLoader public synchronized void nonStaticSynchronizedMethod(){ staticSynchronizedMethod(); } public static synchronized void staticSynchronizedMethod(){ .... }
/* this locks on the instance object that contains the method and any method can call staticNonSynchronizedMethod() method at the same time */ public synchronized void nonStaticSynchronizedMethod(){ staticNonSynchronizedMethod(); } public static void staticNonSynchronizedMethod(){ .... }
/*this locks on the instance object that contains the method and any method can call nonStaticNonSynchronizedMethod() method at the same time */ public synchronized void nonStaticSynchronizedMethod(){ nonStaticNonSynchronizedMethod(); } public void nonStaticNonSynchronizedMethod(){ .... }
//any method can call staticNonSynchronizedMethod at the same time public static synchronized void staticSynchronizedMethod(){ staticNonSynchronizedMethod(); } public static void staticNonSynchronizedMethod(){ .... }
//any method can call staticNonSynchronizedMethod at the same time public static synchronized void staticSynchronizedMethod(){ nonStaticNonSynchronizedMethod(); } public void nonStaticNonSynchronizedMethod(){ .... }Download examples here
Monday, 2 July 2012
What is the difference between HttpServletResponse methods setHeader(), addHeader() and setIntHeader()?
void setHeader(String name, String value)
If a header with this name already in response, then that header value is replaced with this value. Otherwise adds a new header and value to the response.
void addHeader(String name, String value)
If a header with this name already in response, then adds an additional value to the existing header. Otherwise adds a new header and value to the response.
void setIntHeader(String name, int value)
If a integer type header with this name already in response, then replaces that header value with this new integer value. Otherwise adds a new header and value in response.
If a header with this name already in response, then that header value is replaced with this value. Otherwise adds a new header and value to the response.
void addHeader(String name, String value)
If a header with this name already in response, then adds an additional value to the existing header. Otherwise adds a new header and value to the response.
void setIntHeader(String name, int value)
If a integer type header with this name already in response, then replaces that header value with this new integer value. Otherwise adds a new header and value in response.
Tuesday, 26 June 2012
How to find difference between two dates in JavaScript?
var fromDate = new Date(document.getElementById('date1').value); (or) var d = new Date("15/02/2011"); alert(d.getTime()); alert(Date.parse(d)); var toDate = new Date(document.getElementById('date2').value); var daysDifference = Math.ceil((toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24));
How to get custom object from a query instead of object[] when you query for multiple properties of an Entity?
Suppose you have a Customer entity,
Customer.java
So you need to do like the below,
MinCustomer.java
Customer.java
public class Customer implements Serializable{ private Long id; private String firstName; private String lastName; private Long mobileNo; private String houseNo; private String street; //setters and getters }
Query query = entityManager.createQuery("SELECT customer.firstName, customer.mobileNo FROM Customer customer WHERE customer.id = 10");If you execute the above query you will get an Object[], then you have to typecast each array element into corresponding type, this is rediculous.
So you need to do like the below,
Query query = entityManager.createQuery("SELECT new MinCustomer(customer.firstName, customer.mobileNo) FROM Customer customer WHERE customer.id = 10");And create a class MinCustomer with argumentative constructor as given below
MinCustomer minCustomer = query.getSingleResult();
MinCustomer.java
public class MinCustomer{ private String firstName; private Long mobileNo; public MinCustomer(String firstName, Long mobileNo){ this.firstName = firstName; this.mobileNo = mobileNo; } }
Difference between GET and POST methods?
S.No | GET | POST |
---|---|---|
1 | GET is the simplest method of HTTP, and the point of get is to get something back from server. | POST is more powerful request, it's like GET++. With POST, you can request something and at the same time you can send form data to the server. |
2 | With GET, you can send limited(depending on server) amount of data. | With POST, you can send large amount of data. |
3 | The data you sent with GET is appended with url up in the browser bar, so whatever you send is exposed. Better not put sensitive data(like password etc..) as part of GET. | The data you sent with POST is not exposed in url, so data is secured. And you can send large amount of data, files also. |
4 | With GET, you can bookmark page. | With POST, you can't bookmark page |
5 | Data transmission is faster. | Data transmission is slow. |
6 | This is the default method for most of the browsers. | POST is not default method and should be explicitly specified. |
7 | GET is idempotent. | POST is not idempotent. |
Monday, 25 June 2012
String literal vs. String object
1. Direct Method of creating String object
You've probably heard of the "String Literal Pool." What is the String Literal Pool? Most often, I hear people say that it is a collection of String objects. Although that's close, it's not exactly correct. "Really, it's a collection of references to String objects". Strings, even though they are immutable, are still objects like any other in Java. Objects are created on the heap and Strings are no exception. So, Strings that are part of the "String Literal Pool" still live on the heap, but they have references to them from the String Literal Pool.
Strings are immutable and can be shared without any data corruption. For example, if several reference variables refer to the same String object then it would be bad if any of them changes the String’s value. This is the reason for making String objects as immutable.
Take a look at this example:
When a .java file is compiled into a .class file, any String literals are noted in a special way, just as all constants are. When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for String literals. When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the constant table. Once a reference is made to that String object, any references to that String literal throughout your program are simply replaced with the reference to the object referenced from the String Literal Pool.
So, in the example shown above, there would be only one entry in the String Literal Pool, which would refer to a String object that contained the word "java". Both of the local variables, one and two, would be assigned a reference to that single String object. You can see that this is true by looking at the output of the above program. While the equals() method checks to see if the String objects contain the same data ("java"), the == operator, when used on objects, checks for referential equality - that means that it will return true if and only if the two reference variables refer to the exact same object. In such a case, the references are equal. From the above output, you can see that the local variables, one and two, not only refer to Strings that contain the same data, they refer to the same object.
Graphically, our objects and references would look something like this:
2. Creating String using constructor
Note, however, that this is a special behavior for String Literals. Constructing Strings using the "new" keyword implies a different sort of behavior. Let's look at an example:
Source Code
In such a case, although the two String references refer to String objects that contain the same data, "java", they do not refer to the same object. That can be seen from the output of the program. While the equals() method returns true, the == operator, which checks for referential equality, returns false, indicating that the two variables refer to distinct String objects.
Once again, if you'd like to see this graphically, it would look something like this. Note that the String object referenced from the String Literal Pool is created when the class is loaded while the other String object is created at runtime, when the "new String..." line is executed.
If you'd like to get both of these local variables to refer to the same object, you can use the intern() method defined in String. Invoking two.intern() will look for a String object referenced from the String Literal Pool that has the same value as the one you invoked the intern method upon. If one is found, a reference to that String is returned and can be assigned to your local variable. If you did so, you'd have a picture that looks just like the one below, with both local variables, one and two, referring to the same String object, which is also referenced from the String Literal Pool. At that point, the second String object, which was created at run-time, would be eligible for garbage collection.
Strings Garbage Collection
An object is eligible for garbage collection when it is no longer referenced from an active part of the application. Anyone see what is special about garbage collection for String literals? Let's look at an example and see if you can see where this is going.
Source Code
The answer is 1. Unlike most objects, String literals always have a reference to them from the String Literal Pool. That means that they always have a reference to them and are, therefore, not eligible for garbage collection. This is the same example as I used above so you can see what our picture looked liked originally there. Once we assign our variables, one and two, to null, we end up with a picture that looks like this:
As you can see, even though neither of our local variables, one or two, refer to our String object, there is still a reference to it from the String Literal Pool. Therefore, the object is not elgible for garbage collection. The object is always reachable through use of the intern() method, as referred to earlier.
You've probably heard of the "String Literal Pool." What is the String Literal Pool? Most often, I hear people say that it is a collection of String objects. Although that's close, it's not exactly correct. "Really, it's a collection of references to String objects". Strings, even though they are immutable, are still objects like any other in Java. Objects are created on the heap and Strings are no exception. So, Strings that are part of the "String Literal Pool" still live on the heap, but they have references to them from the String Literal Pool.
Strings are immutable and can be shared without any data corruption. For example, if several reference variables refer to the same String object then it would be bad if any of them changes the String’s value. This is the reason for making String objects as immutable.
Take a look at this example:
public class ImmutableStrings { public static void main(String[] args) { String one = "java"; String two = "java"; System.out.println(one.equals(two)); System.out.println(one == two); } } //Output true trueIn such a case, there is really no need to make two instances of an identical String object. If a String object could be changed, as a StringBuffer can be changed, we would be forced to create two separate objects. But, as we know that String objects cannot change, we can safely share a String object among the two String references, one and two. This is done through the String literal pool. Here's how it is accomplished:
When a .java file is compiled into a .class file, any String literals are noted in a special way, just as all constants are. When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for String literals. When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the constant table. Once a reference is made to that String object, any references to that String literal throughout your program are simply replaced with the reference to the object referenced from the String Literal Pool.
So, in the example shown above, there would be only one entry in the String Literal Pool, which would refer to a String object that contained the word "java". Both of the local variables, one and two, would be assigned a reference to that single String object. You can see that this is true by looking at the output of the above program. While the equals() method checks to see if the String objects contain the same data ("java"), the == operator, when used on objects, checks for referential equality - that means that it will return true if and only if the two reference variables refer to the exact same object. In such a case, the references are equal. From the above output, you can see that the local variables, one and two, not only refer to Strings that contain the same data, they refer to the same object.
Graphically, our objects and references would look something like this:
2. Creating String using constructor
Note, however, that this is a special behavior for String Literals. Constructing Strings using the "new" keyword implies a different sort of behavior. Let's look at an example:
Source Code
public class ImmutableStrings { public static void main(String[] args) { String one = "java"; String two = new String("java"); System.out.println(one.equals(two)); System.out.println(one == two); } } //Output true falseIn this case, we actually end up with a slightly different behavior because of the keyword "new." In such a case, references to the two String literals are still put into the constant table (the String Literal Pool), but, when you come to the keyword "new," the JVM is obliged to create a new String object at run-time, rather than using the one from the constant table.
In such a case, although the two String references refer to String objects that contain the same data, "java", they do not refer to the same object. That can be seen from the output of the program. While the equals() method returns true, the == operator, which checks for referential equality, returns false, indicating that the two variables refer to distinct String objects.
Once again, if you'd like to see this graphically, it would look something like this. Note that the String object referenced from the String Literal Pool is created when the class is loaded while the other String object is created at runtime, when the "new String..." line is executed.
If you'd like to get both of these local variables to refer to the same object, you can use the intern() method defined in String. Invoking two.intern() will look for a String object referenced from the String Literal Pool that has the same value as the one you invoked the intern method upon. If one is found, a reference to that String is returned and can be assigned to your local variable. If you did so, you'd have a picture that looks just like the one below, with both local variables, one and two, referring to the same String object, which is also referenced from the String Literal Pool. At that point, the second String object, which was created at run-time, would be eligible for garbage collection.
Strings Garbage Collection
An object is eligible for garbage collection when it is no longer referenced from an active part of the application. Anyone see what is special about garbage collection for String literals? Let's look at an example and see if you can see where this is going.
Source Code
public class ImmutableStrings { public static void main(String[] args) { String one = "someString"; String two = new String("someString"); one = two = null; } }Just before the main method ends, how many objects are available for garbage collection? 0? 1? 2?
The answer is 1. Unlike most objects, String literals always have a reference to them from the String Literal Pool. That means that they always have a reference to them and are, therefore, not eligible for garbage collection. This is the same example as I used above so you can see what our picture looked liked originally there. Once we assign our variables, one and two, to null, we end up with a picture that looks like this:
As you can see, even though neither of our local variables, one or two, refer to our String object, there is still a reference to it from the String Literal Pool. Therefore, the object is not elgible for garbage collection. The object is always reachable through use of the intern() method, as referred to earlier.
Friday, 22 June 2012
Can we override static method in Java?
Many people have heard that you can't override a static method. This is true - you can't. However it is possible to write code like this:
So what's the difference?
Briefly, when you override a method, you still get the benefits of run-time polymorphism, and when you hide, you don't. So what does that mean? Take a look at this code:
Why do we get instanceMethod from Bar, but classMethod() from Foo?
Aren't we using the same instance foo to access both of these? Yes we are - but since one is overriding and the other is hiding, we see different behavior.
Since instanceMethod() is an instance method, in which Bar overrides the method from Foo, at run time the JVM uses the actual class of the instance foo to determine which method to run. Although foo was declared as a Foo, the actual instance we created was a new Bar(). So at runtime, the JVM finds that foo is a Bar instance, and so it calls instanceMethod() in Bar rather than the one in Foo. That's how Java normally works for instance methods.
With classMethod() though. since it's a class method, the compiler and JVM don't expect to need an actual instance to invoke the method. And even if you provide one (which we did: the instance referred to by foo) the JVM will never look at it. The compiler will only look at the declared type of the reference, and use that declared type to determine, at compile time, which method to call. Since foo is declared as type Foo, the compiler looks at foo.classMethod() and decides it means Foo.classMethod. It doesn't matter that the instance reffered to by foo is actually a Bar - for static methods, the compiler only uses the declared type of the reference. That's what we mean when we say a static method does not have run-time polymorphism.
Because instance methods and class methods have this important difference in behavior, we use different terms - "overriding" for instance methods and "hiding" for class methods - to distinguish between the two cases. And when we say you can't override a static method, what that means is that even if you write code that looks like it's overriding a static method (like the first Foo and Bar at the top of this page) - it won't behave like an overridden method.
So what about accessing a static method using an instance?
It's possible in Java to write something like:
foo.classMethod();
where foo is an instance of some class, and classMethod() is a class method (i.e. a static method) of that class. This is legal, but it's a bad idea because it creates confusion. The actual instance foo is not really important here. Only the declared type of foo matters. That is, what class is foo declared to be? Since classMethod() is static, the class of foo (as determined by the compiler at compile time) is all we need.
Rather than writing:
foo.classMethod();
It would be better coding style to write either:
Foo.classMethod();
(or)
Bar.classMethod();
That way, it is crystal clear which class method you would like to call. It is also clear that the method you are calling is indeed a class method.
Barring that, you could always come up with this monstrosity:
foo.getClass().getMethod("classMethod", new Class[]).invoke(null, new Object[]);
But all this could be avoided by simply not trying to override your static (class) methods. :-)
Why does the compiler sometimes talk about overriding static methods?
Sometimes you will see error messages from the compiler that talk about overriding static methods. Apparently, whoever writes these particular messages has not read the Java Language Specification and does not know the difference between overriding and hiding. So they use incorrect and misleading terminology. Just ignore it. The Java Language Specification is very clear about the difference between overriding and hiding, even if the compiler messages are not. Just pretend that the compiler said "hide" rather than "override"..
class Foo { public static void method() { System.out.println("in Foo"); } } class Bar extends Foo { public static void method() { System.out.println("in Bar"); } }This compiles and runs just fine. Isn't it an example of a static method overriding another static method? The answer is no - it's an example of a static method hiding another static method. If you try to override a static method, the compiler doesn't actually stop you - it just doesn't do what you think it does.
So what's the difference?
Briefly, when you override a method, you still get the benefits of run-time polymorphism, and when you hide, you don't. So what does that mean? Take a look at this code:
class Foo { public static void classMethod() { System.out.println("classMethod() in Foo"); } public void instanceMethod() { System.out.println("instanceMethod() in Foo"); } } class Bar extends Foo { public static void classMethod() { System.out.println("classMethod() in Bar"); } public void instanceMethod() { System.out.println("instanceMethod() in Bar"); } } class Test { public static void main(String[] args) { Foo foo = new Bar(); foo.instanceMethod(); foo.classMethod(); } }If you run the above program, the output is
Why do we get instanceMethod from Bar, but classMethod() from Foo?
Aren't we using the same instance foo to access both of these? Yes we are - but since one is overriding and the other is hiding, we see different behavior.
Since instanceMethod() is an instance method, in which Bar overrides the method from Foo, at run time the JVM uses the actual class of the instance foo to determine which method to run. Although foo was declared as a Foo, the actual instance we created was a new Bar(). So at runtime, the JVM finds that foo is a Bar instance, and so it calls instanceMethod() in Bar rather than the one in Foo. That's how Java normally works for instance methods.
With classMethod() though. since it's a class method, the compiler and JVM don't expect to need an actual instance to invoke the method. And even if you provide one (which we did: the instance referred to by foo) the JVM will never look at it. The compiler will only look at the declared type of the reference, and use that declared type to determine, at compile time, which method to call. Since foo is declared as type Foo, the compiler looks at foo.classMethod() and decides it means Foo.classMethod. It doesn't matter that the instance reffered to by foo is actually a Bar - for static methods, the compiler only uses the declared type of the reference. That's what we mean when we say a static method does not have run-time polymorphism.
Because instance methods and class methods have this important difference in behavior, we use different terms - "overriding" for instance methods and "hiding" for class methods - to distinguish between the two cases. And when we say you can't override a static method, what that means is that even if you write code that looks like it's overriding a static method (like the first Foo and Bar at the top of this page) - it won't behave like an overridden method.
So what about accessing a static method using an instance?
It's possible in Java to write something like:
foo.classMethod();
where foo is an instance of some class, and classMethod() is a class method (i.e. a static method) of that class. This is legal, but it's a bad idea because it creates confusion. The actual instance foo is not really important here. Only the declared type of foo matters. That is, what class is foo declared to be? Since classMethod() is static, the class of foo (as determined by the compiler at compile time) is all we need.
Rather than writing:
foo.classMethod();
It would be better coding style to write either:
Foo.classMethod();
(or)
Bar.classMethod();
That way, it is crystal clear which class method you would like to call. It is also clear that the method you are calling is indeed a class method.
Barring that, you could always come up with this monstrosity:
foo.getClass().getMethod("classMethod", new Class[]).invoke(null, new Object[]);
But all this could be avoided by simply not trying to override your static (class) methods. :-)
Why does the compiler sometimes talk about overriding static methods?
Sometimes you will see error messages from the compiler that talk about overriding static methods. Apparently, whoever writes these particular messages has not read the Java Language Specification and does not know the difference between overriding and hiding. So they use incorrect and misleading terminology. Just ignore it. The Java Language Specification is very clear about the difference between overriding and hiding, even if the compiler messages are not. Just pretend that the compiler said "hide" rather than "override"..
Wednesday, 20 June 2012
Java program to check the given number is prime or not.
package com.dev.test; import java.util.Scanner; public class PrimeNumber { public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.print("Enter number : "); while (in.hasNext()){ int num = in.nextInt(); if (isPrime(num)) { System.out.println(num + " is prime number"); } else { System.out.println(num + " is not a prime number"); } System.out.print("Enter number : "); } } public static boolean isPrime(int num) { //check if n is 2 if (num == 2){ return true; } //check if n is a multiple of 2 if (num % 2 == 0){ return false; } //if not, then just check the odds for (int i = 3; i * i <= num; i += 2) { if (num % i == 0) return false; } return true; } }
What is metadata?
Metadata is simply data about data. It defines the structure and meaning of data objects. Examples of metadata include database schema, the meaning of object attributes and methods in a Java class, annotations in a Java class, XML DTDs and Schemas, and UML models.
What does volatile do?
Java volatile keyword cannot be used with method or class and it can only be used with variables.
This is probably best explained by comparing the effects that volatile and synchronized have on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:
On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.
Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:
1) The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
2) The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory (JVMs can use dirty sets to optimize this so that only "dirty" variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
3) The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
4) (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
5) The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
This is probably best explained by comparing the effects that volatile and synchronized have on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:
int i1; volatile int i2; int i3; int geti1() {return i1;} int geti2() {return i2;} synchronized int geti3() {return i3;}geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.
On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.
Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:
1) The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
2) The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory (JVMs can use dirty sets to optimize this so that only "dirty" variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
3) The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
4) (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
5) The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
Monday, 18 June 2012
Program for printing numbers from 1 to 100, which contains digit 5?
public class PrintNumbers { public static void main(String[] args) { for (int i = 0; i <= 100; i++) { if (isContainGivenNo(i, 5)) { System.out.println(i); } } } private static boolean isContainGivenNo(int no, int containNo) { while (no > 9) { int remainder = no % 10; if (remainder == containNo) { return true; } no /= 10; } return no == containNo; } }(or)
public class PrintNumbers { public static void main(String[] args){ for(int i = 1; i < 100; i++){ String s = ""+i; if (s.contains("5")){ System.out.println(i); } } } }Output : 5 15 25 35 45 51 52 53 54 55 56 57 58 59 65 75 85 95
Sunday, 17 June 2012
What is the difference between thread and threadlocal?
Thread represents the flow of control, i.e. the code that is running as a thread. It can be started, interrupted, waited for, assigned a priority, etc.
ThreadLocal represents a piece of memory attached to the thread. It's a single object that maintains a different value for each thread that uses it. When a thread calls Set on a ThreadLocal, it will get back the same value later, even if other threads have also called set on the same ThreadLocal in the intervening time. Each will get back its own value.
You could achieve the same result with a Map<Thread, ?>, where the current thread is always the key, but this is neater and already checked to be thread-safe.
ThreadLocal represents a piece of memory attached to the thread. It's a single object that maintains a different value for each thread that uses it. When a thread calls Set on a ThreadLocal, it will get back the same value later, even if other threads have also called set on the same ThreadLocal in the intervening time. Each will get back its own value.
You could achieve the same result with a Map<Thread, ?>, where the current thread is always the key, but this is neater and already checked to be thread-safe.
Friday, 8 June 2012
Wednesday, 23 May 2012
Difference between Joint Point and Point Cut?Please explain with example or real life terminology?
When you go out to a restaurant, you look at a menu and see several options to choose from. You can order one or more of any of the items on the menu. But until you actually order them, they are just "opportunities to dine". Once you place the order and the waiter brings it to your table, it's a meal.
Join points are the options on the menu and pointcuts are the items you select. A joinpoint is an opportunity within code for you to apply an aspect...just an opportunity. Once you take that opportunity and select one or more joinpoints and apply an aspect to them, you've got a pointcut.
Thursday, 29 March 2012
CRON EXPRESSION
CRON Expression:
A CRON expression is a string comprising 5 or 6 fields separated by white space that represents a set of times, normally as a schedule to execute some routine.
A CRON expression is a string comprising 5 or 6 fields separated by white space that represents a set of times, normally as a schedule to execute some routine.
Field name | Mandatory? | Allowed values | Allowed special characters |
---|---|---|---|
Minutes | Yes | 0-59 | * / , - |
Hours | Yes | 0-23 | * / , - |
Day of month | Yes | 1-31 | * / , - ? L W |
Month | Yes | 1-12 or JAN-DEC | * / , - |
Day of week | Yes | 0-6 or SAT-FRI | * / , - ? L # |
Year | No | 1970–2099 | * / , - |
Special characters
- Asterisk ( * )
- The asterisk indicates that the cron expression will match for all values of the field; e.g., using an asterisk in the 4th field (month) would indicate every month.
- Slash ( / )
- Slashes are used to describe increments of ranges. For example 3-59/15 in the 1st field (minutes) would indicate the 3rd minute of the hour and every 15 minutes thereafter. The form "*/..." is equivalent to the form "first-last/...", that is, an increment over the largest possible range of the field.
- Percent ( % )
- Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.
- Comma ( , )
- Commas are used to separate items of a list. For example, using "MON,WED,FRI" in the 5th field (day of week) would mean Mondays, Wednesdays and Fridays.
- Hyphen ( - )
- Hyphens are used to define ranges. For example, 2000-2010 would indicate every year between 2000 and 2010 CE inclusive.
- L
- 'L' stands for "last". When used in the day-of-week field, it allows you to specify constructs such as "the last Friday" ("5L") of a given month. In the day-of-month field, it specifies the last day of the month.
- W
- The 'W' character is allowed for the day-of-month field. This character is used to specify the weekday (Monday-Friday) nearest the given day. As an example, if you were to specify "15W" as the value for the day-of-month field, the meaning is: "the nearest weekday to the 15th of the month". So if the 15th is a Saturday, the trigger will fire on Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th. However if you specify "1W" as the value for day-of-month, and the 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not 'jump' over the boundary of a month's days. The 'W' character can be specified only when the day-of-month is a single day, not a range or list of days.
- Hash ( # )
- '#' is allowed for the day-of-week field, and must be followed by a number between one and five. It allows you to specify constructs such as "the second Friday" of a given month.
- Question mark ( ? )
- Note: Question mark is a non-standard character and exists only in some cron implementations. It is used instead of '*' for leaving either day-of-month or day-of-week blank.
Examples
Every minute
* * * * *
Every 1 minute
*/1 * * * *
or
0 0/1 * * * ?
23:00:00 every weekday night
0 23 ? * MON-FRI
In 2003 on the 11th to 26th of each month from January to June every third minute starting from 2 past 1am, 9am and 10pm
2-59/3 1,9,22 11-26 1-6 ? 2003
Minutes | Hours | Day of month | Month | Weekday | Year | |
---|---|---|---|---|---|---|
Every 2 hours at :30 | 30 | 0/2 or */2 | * | * | ? | * |
Every day at 11:45PM | 45 | 23 | * | * | ? | * |
Every Sunday at 1:00AM | 0 | 1 | ? | * | 0 | * |
Every last day of month at 10:00AM and 10:00PM |
0 | 10,22 | L | * | ? | * |
Wednesday, 28 March 2012
Char codes for all keyboard keys.
|
|
|
Monday, 26 March 2012
How to get value from properties file in java class using spring?
To get property key-value from .properties file,
1) Declare <context:property-placeholder> tag in spring xml.
2) Declare a variable with required type and annotate the variable with @value.
Ex:
env.properties
--------------
user.name=prabha
user.has.phone=true
in java class
------------
@value("${useer.name}")
private String name;
@value("${user.has.phone}")
private boolean hasPhone;
//setters and getters
1) Declare <context:property-placeholder> tag in spring xml.
2) Declare a variable with required type and annotate the variable with @value.
Ex:
env.properties
--------------
user.name=prabha
user.has.phone=true
in java class
------------
@value("${useer.name}")
private String name;
@value("${user.has.phone}")
private boolean hasPhone;
//setters and getters
How to restrict ctrl+v in textbox?
The simplest way to restrict ctrl+v in textbox is,
declare onpaste, oncopy, oncontextmenu attributes in body.
Ex:
<body onpaste="return false" oncopy="return false" oncontextmenu="return false">
........
</body>
the above will restrict ctrl+v, ctrl+c, right click in all textbox's.
To restrict ctrl+v in individual textbox,
<input type="text" onpaste="return false" oncopy="return false" oncontextmenu="return false">
onpaste : restricts ctrl+v
oncopy : restricts ctrl+c
oncontextmenu : restricts right click in textbox
declare onpaste, oncopy, oncontextmenu attributes in body.
Ex:
<body onpaste="return false" oncopy="return false" oncontextmenu="return false">
........
</body>
the above will restrict ctrl+v, ctrl+c, right click in all textbox's.
To restrict ctrl+v in individual textbox,
<input type="text" onpaste="return false" oncopy="return false" oncontextmenu="return false">
onpaste : restricts ctrl+v
oncopy : restricts ctrl+c
oncontextmenu : restricts right click in textbox
Subscribe to:
Posts (Atom)