Java stuff you didn't know you didn't know [duplicate] - java

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
After reading Hidden Features of C# I wondered, What are some of the hidden features of Java?

Double Brace Initialization took me by surprise a few months ago when I first discovered it, never heard of it before.
ThreadLocals are typically not so widely known as a way to store per-thread state.
Since JDK 1.5 Java has had extremely well implemented and robust concurrency tools beyond just locks, they live in java.util.concurrent and a specifically interesting example is the java.util.concurrent.atomic subpackage that contains thread-safe primitives that implement the compare-and-swap operation and can map to actual native hardware-supported versions of these operations.

Joint union in type parameter variance:
public class Baz<T extends Foo & Bar> {}
For example, if you wanted to take a parameter that's both Comparable and a Collection:
public static <A, B extends Collection<A> & Comparable<B>>
boolean foo(B b1, B b2, A a) {
return (b1.compareTo(b2) == 0) || b1.contains(a) || b2.contains(a);
}
This contrived method returns true if the two given collections are equal or if either one of them contains the given element, otherwise false. The point to notice is that you can invoke methods of both Comparable and Collection on the arguments b1 and b2.

I was surprised by instance initializers the other day. I was deleting some code-folded methods and ended up creating multiple instance initializers :
public class App {
public App(String name) { System.out.println(name + "'s constructor called"); }
static { System.out.println("static initializer called"); }
{ System.out.println("instance initializer called"); }
static { System.out.println("static initializer2 called"); }
{ System.out.println("instance initializer2 called"); }
public static void main( String[] args ) {
new App("one");
new App("two");
}
}
Executing the main method will display:
static initializer called
static initializer2 called
instance initializer called
instance initializer2 called
one's constructor called
instance initializer called
instance initializer2 called
two's constructor called
I guess these would be useful if you had multiple constructors and needed common code
They also provide syntactic sugar for initializing your classes:
List<Integer> numbers = new ArrayList<Integer>(){{ add(1); add(2); }};
Map<String,String> codes = new HashMap<String,String>(){{
put("1","one");
put("2","two");
}};

JDK 1.6_07+ contains an app called VisualVM (bin/jvisualvm.exe) that is a nice GUI on top of many of the tools. It seems more comprehensive than JConsole.

Classpath wild cards since Java 6.
java -classpath ./lib/* so.Main
Instead of
java -classpath ./lib/log4j.jar:./lib/commons-codec.jar:./lib/commons-httpclient.jar:./lib/commons-collections.jar:./lib/myApp.jar so.Main
See http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html

For most people I interview for Java developer positions labeled blocks are very surprising. Here is an example:
// code goes here
getmeout:{
for (int i = 0; i < N; ++i) {
for (int j = i; j < N; ++j) {
for (int k = j; k < N; ++k) {
//do something here
break getmeout;
}
}
}
}
Who said goto in java is just a keyword? :)

How about covariant return types which have been in place since JDK 1.5? It is pretty poorly publicised, as it is an unsexy addition, but as I understand it, is absolutely necessary for generics to work.
Essentially, the compiler now allows a subclass to narrow the return type of an overridden method to be a subclass of the original method's return type. So this is allowed:
class Souper {
Collection<String> values() {
...
}
}
class ThreadSafeSortedSub extends Souper {
#Override
ConcurrentSkipListSet<String> values() {
...
}
}
You can call the subclass's values method and obtain a sorted thread safe Set of Strings without having to down cast to the ConcurrentSkipListSet.

Transfer of control in a finally block throws away any exception. The following code does not throw RuntimeException -- it is lost.
public static void doSomething() {
try {
//Normally you would have code that doesn't explicitly appear
//to throw exceptions so it would be harder to see the problem.
throw new RuntimeException();
} finally {
return;
}
}
From http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html

Haven't seen anyone mention instanceof being implemented in such a way that checking for null is not necessary.
Instead of:
if( null != aObject && aObject instanceof String )
{
...
}
just use:
if( aObject instanceof String )
{
...
}

Allowing methods and constructors in enums surprised me. For example:
enum Cats {
FELIX(2), SHEEBA(3), RUFUS(7);
private int mAge;
Cats(int age) {
mAge = age;
}
public int getAge() {
return mAge;
}
}
You can even have a "constant specific class body" which allows a specific enum value to override methods.
More documentation here.

The type params for generic methods can be specified explicitly like so:
Collections.<String,Integer>emptyMap()

You can use enums to implement an interface.
public interface Room {
public Room north();
public Room south();
public Room east();
public Room west();
}
public enum Rooms implements Room {
FIRST {
public Room north() {
return SECOND;
}
},
SECOND {
public Room south() {
return FIRST;
}
}
public Room north() { return null; }
public Room south() { return null; }
public Room east() { return null; }
public Room west() { return null; }
}
EDIT: Years later....
I use this feature here
public enum AffinityStrategies implements AffinityStrategy {
https://github.com/peter-lawrey/Java-Thread-Affinity/blob/master/src/main/java/vanilla/java/affinity/AffinityStrategies.java
By using an interface, developers can define their own strategies. Using an enum means I can define a collection (of five) built in ones.

As of Java 1.5, Java now has a much cleaner syntax for writing functions of variable arity. So, instead of just passing an array, now you can do the following
public void foo(String... bars) {
for (String bar: bars)
System.out.println(bar);
}
bars is automatically converted to array of the specified type. Not a huge win, but a win nonetheless.

My favorite: dump all thread stack traces to standard out.
windows: CTRL-Break in your java cmd/console window
unix: kill -3 PID

A couple of people have posted about instance initializers, here's a good use for it:
Map map = new HashMap() {{
put("a key", "a value");
put("another key", "another value");
}};
Is a quick way to initialize maps if you're just doing something quick and simple.
Or using it to create a quick swing frame prototype:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add( new JLabel("Hey there"){{
setBackground(Color.black);
setForeground( Color.white);
}});
panel.add( new JButton("Ok"){{
addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent ae ){
System.out.println("Button pushed");
}
});
}});
frame.add( panel );
Of course it can be abused:
JFrame frame = new JFrame(){{
add( new JPanel(){{
add( new JLabel("Hey there"){{
setBackground(Color.black);
setForeground( Color.white);
}});
add( new JButton("Ok"){{
addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent ae ){
System.out.println("Button pushed");
}
});
}});
}});
}};

Dynamic proxies (added in 1.3) allow you to define a new type at runtime that conforms to an interface. It's come in handy a surprising number of times.

final initialization can be postponed.
It makes sure that even with a complex flow of logic return values are always set. It's too easy to miss a case and return null by accident. It doesn't make returning null impossible, just obvious that it's on purpose:
public Object getElementAt(int index) {
final Object element;
if (index == 0) {
element = "Result 1";
} else if (index == 1) {
element = "Result 2";
} else {
element = "Result 3";
}
return element;
}

I think another "overlooked" feature of java is the JVM itself. It is probably the best VM available. And it supports lots of interesting and useful languages (Jython, JRuby, Scala, Groovy). All those languages can easily and seamlessly cooperate.
If you design a new language (like in the scala-case) you immediately have all the existing libraries available and your language is therefore "useful" from the very beginning.
All those languages make use of the HotSpot optimizations. The VM is very well monitor and debuggable.

You can define an anonymous subclass and directly call a method on it even if it implements no interfaces.
new Object() {
void foo(String s) {
System.out.println(s);
}
}.foo("Hello");

The asList method in java.util.Arrays allows a nice combination of varargs, generic methods and autoboxing:
List<Integer> ints = Arrays.asList(1,2,3);

Using this keyword for accessing fields/methods of containing class from an inner class. In below, rather contrived example, we want to use sortAscending field of container class from the anonymous inner class. Using ContainerClass.this.sortAscending instead of this.sortAscending does the trick.
import java.util.Comparator;
public class ContainerClass {
boolean sortAscending;
public Comparator createComparator(final boolean sortAscending){
Comparator comparator = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
if (sortAscending || ContainerClass.this.sortAscending) {
return o1 - o2;
} else {
return o2 - o1;
}
}
};
return comparator;
}
}

Not really a feature, but an amusing trick I discovered recently in some Web page:
class Example
{
public static void main(String[] args)
{
System.out.println("Hello World!");
http://Phi.Lho.free.fr
System.exit(0);
}
}
is a valid Java program (although it generates a warning).
If you don't see why, see Gregory's answer! ;-) Well, syntax highlighting here also gives a hint!

This is not exactly "hidden features" and not very useful, but can be extremely interesting in some cases:
Class sun.misc.Unsafe - will allow you to implement direct memory management in Java (you can even write self-modifying Java code with this if you try a lot):
public class UnsafeUtil {
public static Unsafe unsafe;
private static long fieldOffset;
private static UnsafeUtil instance = new UnsafeUtil();
private Object obj;
static {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
unsafe = (Unsafe)f.get(null);
fieldOffset = unsafe.objectFieldOffset(UnsafeUtil.class.getDeclaredField("obj"));
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}

When working in Swing I like the hidden Ctrl - Shift - F1 feature.
It dumps the component tree of the current window.
(Assuming you have not bound that keystroke to something else.)

Every class file starts with the hex value 0xCAFEBABE to identify it as valid JVM bytecode.
(Explanation)

My vote goes to java.util.concurrent with its concurrent collections and flexible executors allowing among others thread pools, scheduled tasks and coordinated tasks. The DelayQueue is my personal favorite, where elements are made available after a specified delay.
java.util.Timer and TimerTask may safely be put to rest.
Also, not exactly hidden but in a different package from the other classes related to date and time. java.util.concurrent.TimeUnit is useful when converting between nanoseconds, microseconds, milliseconds and seconds.
It reads a lot better than the usual someValue * 1000 or someValue / 1000.

Language-level assert keyword.

Not really part of the Java language, but the javap disassembler which comes with Sun's JDK is not widely known or used.

The addition of the for-each loop construct in 1.5. I <3 it.
// For each Object, instantiated as foo, in myCollection
for(Object foo: myCollection) {
System.out.println(foo.toString());
}
And can be used in nested instances:
for (Suit suit : suits)
for (Rank rank : ranks)
sortedDeck.add(new Card(suit, rank));
The for-each construct is also applicable to arrays, where it hides the index variable rather than the iterator. The following method returns the sum of the values in an int array:
// Returns the sum of the elements of a
int sum(int[] a) {
int result = 0;
for (int i : a)
result += i;
return result;
}
Link to the Sun documentation

i personally discovered java.lang.Void very late -- improves code readability in conjunction with generics, e.g. Callable<Void>

Related

How to deep clone a hash table

I have a project that I need to do very specifically and I need some help. I have looked basically everywhere for an answer and can't find it, not even on Stack Overflow. It has to do with cloning hashtables. (Both shallow and deep.)
I have pasted the code I have below, but in short, I have a class called EHashtable, which extends Hashtable. I then add some string keys and values of various custom class types. In the EHashtable class, there are methods called Clone() and dClone(). Clone() is supposed to create a shallow clone of its Hashtable - meaning the Hashtable is cloned but its values are not. dClone() is supposed to create a new Hashtable and clone each of the original hashtable's values to it (meaning each value points to different memory references than the first). It is also supposed to throw an exception if the custom made object is not cloneable.
Right now, even on a shallow clone (the Clone() method), changes one value in one Hashtable and will NOT change the value in the other. It seems as if each value is pointing to different references. I don't understand how to make the Clone() and dClone() methods do the two different things I want them to do. One other thing, the hashtable cannot have Generics. It needs to be Hashtable and not Hashtable<K, V>.
I have looked up how to for loop through a hashtable. That only works on an Object type, and Object types can't clone() due to the method's protected status. Below is my code, starting with the main method. I realize this is very specific, and all help is greatly appreciated.
import java.util.Hashtable;
import java.util.Iterator;
public class _Test {
public static void main(String[] arguments) {
Circle cr1 = new Circle(1);
Circle cr2 = new Circle(2);
Point po1 = new Point(10, 10);
Point po2 = new Point(20, 20);
PlaneCircle pcr1 = new PlaneCircle(po1, 11f);
PlaneCircle pcr2 = new PlaneCircle(po2, 12f);
EHashtable eh = new EHashtable(20);
eh.add(new String("C1"), cr1);
eh.add(new String("C2"), cr2);
eh.add(new String("PC1"), pcr1);
eh.add(new String("PC2"), pcr2);
try {
EHashtable ehCloned = (EHashtable) eh.Clone();
System.out.println("/***--Before Alteration--***/");
System.out.println("eh:");
System.out.println(eh);
System.out.println();
System.out.println("ehCloned:");
System.out.println(ehCloned);
System.out.println();
Circle cr3 = new Circle(99);
Point po3 = new Point(99, 99);
PlaneCircle pcr3 = new PlaneCircle(po3, 9999f);
eh.add(new String("C1"), cr3);
eh.add(new String("PC1"), pcr3);
System.out.println("/***--After Alteration--***/");
System.out.println("eh:");
System.out.println(eh);
System.out.println();
System.out.println("ehCloned:");
System.out.println(ehCloned);
System.out.println();
}
catch (CloneNotSupportedException e) {
System.out.println(e.toString());
}
catch (ClassCastException e) {
System.out.println(e.toString());
}
catch (Exception e) {
System.out.println("\nError Message:" + e.getMessage());
}
}
}
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
public class EHashtable extends Hashtable {
public EHashtable() {
}
public EHashtable(int capacity) {
}
// Done
public boolean add(Object key, Object value) {
if (!(containsKey(key) && containsValue(value))) {
put(key, value);
return true;
}
else {
return false;
}
}
// Done
public void Clear() {
clear();
}
// Done
public Object Clone() throws CloneNotSupportedException {
EHashtable eh = (EHashtable) this.clone();
return eh;
}
public Object dClone() {
EHashtable eh = new EHashtable();
for (Object key : keySet())
eh.put(key, get(key));
return eh;
}
// Done
public boolean isNotEmpty() {
return !isEmpty();
}
// Done
public Iterator iterate() {
return entrySet().iterator();
}
}
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "[x=" + x + ", y=" + y + "]";
}
}
public class PlaneCircle {
private Point p;
private float radius;
public PlaneCircle (Point p, float radius) {
this.p = p;
this.radius = radius;
}
public String toString() {
return "[p=" + p.toString() + ", radius=" + radius + "]";
}
}
public class Circle {
private float radius;
public Circle(float radius) {
this.radius = radius;
}
public String toString() {
return "[radius=" + radius + "]";
}
}
Simplest way is to serialize and deserialize the HashMap. However this requires to implement Serializable on all key and value classes. However wether its Cloneable or Serializable .. there is some work ´to be done in order to deep-copy object graphs anyway
Preferably with a fast serializer like http://code.google.com/p/fast-serialization/ :-). This way performance should be ok'ish
Found this in effective java
public class HashTable implements Cloneable {
private Entry[] buckets = ...;
private static class Entry {
final Object key;
Object value;
Entry next;
Entry(Object key, Object value, Entry next) {
this.key = key;
this.value = value;
this.next = next;
}
// Recursively copy the linked list headed by this Entry
Entry deepCopy() {
return new Entry(key, value,
next == null ? null : next.deepCopy());
}
}
#Override public HashTable clone() {
try {
HashTable result = (HashTable) super.clone();
result.buckets = new Entry[buckets.length];
for (int i = 0; i < buckets.length; i++)
if (buckets[i] != null)
result.buckets[i] = buckets[i].deepCopy();
return result;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
One more way to do is:
SerializationUtils.clone() serializes and de-serializes the entire object-graph referenced by the Map, that's why it takes so long. It creates a true deep-copy, however (provided you don't have funny serialization-stuff going on in your classes).
If all the elements are Serializable than serialize the hashMap and deserialize by ObjectInputStream , which will be a deep copy.
Please refer to this.
Some important point from this link:
Cloning through serialization
One solution to these problems is to clone using serialization.
Usually, serialization is used to send objects off somewhere (into a
file or over the network) so that somebody else can reconstruct them
later. But you can abuse it to reconstruct the object yourself
immediately. If the object is serializable at all, then the
reconstruction should be a faithful copy. In normal uses of
serialization, the original object is nowhere near; it could be on the
other side of the world at the far end of a network connection. So you
can be sure that changing the copy will have no effect on the
original.
Before going any further, I should caution that this technique is not
to be used lightly. First of all, serialization is hugely expensive.
It could easily be a hundred times more expensive than the clone()
method. Secondly, not all objects are serializable. Thirdly, making a
class serializable is tricky and not all classes can be relied on to
get it right. (You can assume that system classes are correct,
though.)
In addition to the Serialization ideas, if you have existing code to persist your Map to/from a file, a database, XML/json etc., that would be a "quick and dirty" option for you. Not quick performance wise, but quick to code.
Note that it is a poor idea to have methods which differ only by case (clear, Clear; clone, Clone). It isn't necessary because you can use the super keyword to call the superclass implementation of a method.
Hashtable itself is cloneable, so overriding clone is not necessary; the existing clone method already does what you need for a shallow clone, although for convenience you could override it to give a return type of EHashtable instead of Object:
public EHashtable clone() {
return (EHashtable)super.clone();
}
For a deep clone, you're right, since Object.clone is protected, you can't call it. It's a historical design mistake in Java. There are messy ways around it (serialization, or reflection, or defining an ActuallyCloneable interface that makes the method public) but I don't think you need to do these things, because (unless you left mutator methods out for brevity when pasting the question) all of the types that you're storing in your table seem to be immutable. There is no use in cloning them if they cannot change.
If they're not immutable in your real code, making them immutable is actually a very good idea for these simple value types. It enables you to simplify other code by not worrying about when you need to copy them.
Right now, even on a shallow clone (the Clone() method), changes one value in one Hashtable and will NOT change the value in the other.
You're not changing values; you're putting new ones. Changing values would be something like:
cr1.radius = 123;
That's not possible if your objects are immutable, but it would change the object as seen from both the original hashtable and from its shallow clone.
A couple of minor suggestions: (1) Printing the toString() of an exception will only print its name and message; the stacktrace information will be missing. To get the stacktrace too, use the printStackTrace() method. This also has the benefit of making sure it's printed to stderr instead of stdout (which may make it more visible; it's bright red in Eclipse). E.g.,
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
Or if there is nothing useful that can be done with a particular checked exception, it is better to simply rethrow it as an unchecked exception, so that surrounding code does not plow on in spite of errors:
catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
(2) Doing eh.add(new String("C1"), cr1); (creating a new string) is a silly anti-pattern that has no benefits and adds unnecessary object creation and typing overhead. You can change it to just eh.add("C1", cr1);.

Is there any way I can return a value from a loop and continue from where I left off?

Is there any way I can return a value from a loop and continuing from where I left off ?
In the following snippet, I want to return the current value of currVm. But I am unable to do so.
In the innermost loop of the snippet :
while(c <= currVm) {
allocatedVm(currVm);
c++;
}
a function named allocatedVm is called. I want to return the value of currVm and start again from where I left off. Is there any way out ?
#Override
public int getNextAvailableVm() {
Set<String> dataCenters = confMap.keySet();
for (String dataCenter : dataCenters) {
LinkedList<DepConfAttr> list = confMap.get(dataCenter);
Collections.sort(list, new MemoryComparator());
int size = list.size() - 1;
int count = 0;
while(size >= 0) {
DepConfAttr dca = (DepConfAttr)list.get(count);
int currVm = dca.getVmCount();
int c = 0;
while(c <= currVm) {
allocatedVm(currVm); // RETURN currVm
c++;
}
count++;
size--;
}
}
}
The best approach would probably be to write a method returning an Iterable<Integer>. That's not as easy in Java as it is in languages which support generator functions (e.g. C# and Python) but it's still feasible. If the code is short, you can get away with a pair of (nested) anonymous inner classes:
public Iterable<Integer> foo() {
return new Iterable<Integer>() {
#Override public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
// Implement hasNext, next and remove here
};
}
};
}
In your case I'd be tempted to break it into a separate non-anonymous class though, just for simplicity.
Anyway, the point of using Iterable is that an Iterator naturally has state - that's its purpose, basically. So it's a good fit for your requirements.
Another rather simpler approach would be to return all of the elements in one go, and make the caller perform the allocation on demand. Obviously that doesn't work well if there could be a huge number of elements, but it would be easier to understand.
not sure i understand what you need, but:
if you wish to notify the caller of the method that you've got a value during the running of the method, but don't wish to exit the method just yet, you can use listeners.
just create an interface as a parameter to your function, and have a function inside that will have the object as a parameter.
example:
interface IGotValueListener
{
public void onGotValue(MyClass obj);
}
public int getNextAvailableVm(IGotValueListener listener)
{
...
if(listener!=null)
listener.onGotValue(...);
}
now , for calling the method, you do:
int finalResult=getNextAvailableVm(new IGotValueListener ()
{
... //implement onGotValue
};
You can return from anywhere in your method , by just putting the return keyword. If you want to put a functionality to resume ur method from different places then u need to factor ur method in that way. You can use labels and if statements, set some static variables to mark the last execution place. If your application is not multi-threaded then u need not to worry with the use of static variable synchronization. Also if your method is too big and becoming hard to follow/read, then think about breaking it into smaller ones.

java optimization nitpick: is it faster to cast something and let it throw exception than calling instanceof to check before cast?

Before anyone says anything I'm asking this out of curiosity only; I'm not planning to do any premature optimization based off of this answer.
My question is about speed in using reflection and casting. The standard saying is 'reflection is slow'. My question is what part exactly is slow, and why; particularly in comparing if something is a parent of another instance.
I'm pretty confident that just comparing the class of an object to another Class object is about as fast as any comparison, presumably just doing direct comparison of singleton objects that are already stored int he Object's state; but what if one class is a parent of the other?
I usually think of instanceof as being about as fast as regular class checking, but today I thought about it and it seems that some reflection has to happen 'under the scenes' for instanceof to work. I checked online and found a few places where someone said instanceof is slow; presumably due to reflection required to compare the parent of an object?
This lead to the next question, what about just casting. If I cast something as an object it's not I get a ClassCastException. But this doesn't happen if a cast an object to a parent of itself. Essentially I'm doing an instanceof call, or logic to that effect, when I do the cast at run time am I not? I've never heard anyone hint that casting an object could be slow before. Admittedly not all casts are to a parent of the provided object, but plenty of casts are to parent classes. Yet never has anyone hinted at all that this could be slow.
So which is it. Is instanceof really not that slow? Are both instanceof and casting to parent class kind of slow? or is there some reason a cast can be done faster then an instanceof call?
As always try it and see in your particular situations, but:
-Exceptions are expensive, remarkably so.
-Using exceptions for code flow is almost always a bad idea
Edit:
Ok I was interested so I wrote a quick test system
public class Test{
public Test(){
B b=new B();
C c=new C();
for(int i=0;i<10000;i++){
testUsingInstanceOf(b);
testUsingInstanceOf(c);
testUsingException(b);
testUsingException(c);
}
}
public static void main(String[] args){
Test test=new Test();
}
public static boolean testUsingInstanceOf(A possiblyB){
if (possiblyB instanceof B){
return true;
}else{
return false;
}
}
public static boolean testUsingException(A possiblyB){
try{
B b=(B)possiblyB;
return true;
}catch(Exception e){
return false;
}
}
private class A{
}
private class B extends A{
}
private class C extends A{
}
}
Profile results:
by InstanceOf: 4.43 ms
by Exception: 79.4 ms
as I say, remarkably expensive
And even when its always going to be a B (simulating when you're 99% sure its B you just need to be sure its still no faster:
Profile results when always B:
by InstanceOf: 4.48 ms
by Exception: 4.51 ms
There is a general answer and a particular answer.
General case
if (/* guard against exception */) {
/* do something that would throw an exception */
} else {
/* recover */
}
// versus
try {
/* do something that would throw an exception */
} catch (TheException ex) {
/* recover */
}
It is a fact that creating/throwing/catching an exception is expensive. And they are likely to be significantly more expensive than doing the test. However, that doesn't mean that the "test first" version is always faster. This is because in the "test first" version, the tests may actually be performed: first time in the if, and second time in the code that would throw the exception.
When you take that into account, it is clear that if the cost of the (extra) test is large enough and the relative frequency of exceptions is small enough, "test first" will actually be slower. For example, in:
if (file.exists() && file.isReadable()) {
is = new FileInputStream(file);
} else {
System.err.println("missing file");
}
versus
try {
is = new FileInputStream(file);
} catch (IOException ex) {
System.err.println("missing file");
}
the "test first" approach performs 2 extra system calls, and system calls are expensive. If the "missing file" scenario is also unusual ....
The second confounding factor is that the most recent HotSpot JIT compilers do some significant optimization of exceptions. In particular, if the JIT compiler can figure out that the state of the exception object is not used, it may turn the exception create/throw/catch into a simple jump instruction.
The specific case of instanceof
In this case we are most likely comparing these two:
if (o instanceof Foo) {
Foo f = (Foo) o;
/* ... */
}
// versus
try {
Foo f = (Foo) o;
} catch (ClassCastException ex) {
/* */
}
Here a second optimization occurs. An instanceof followed by a type cast is a common pattern. A HotSpot JIT compiler can often eliminate the dynamic type check that is performed by the type cast ... since this is repeating a test that just succeeded. When you factor this in, it the "test first" version cannot be slower than the "exception" version ... even if the latter is optimized to a jump.
Unfortunately, Richard's code can't be run directly to produce timings. I've modified the question slightly, assuming that you really want "if A is a B, do something on B", rather than just asking the question "is A a B?". Here is the test code.
UPDATED FROM ORIGINAL
It was rather challenging to write trivial code that the HotSpot compiler didn't reduce to nothing, but I think the following is good:
package net.redpoint.utils;
public class Scratch {
public long counter = 0;
public class A {
public void inc() { counter++; }
}
public class B extends A {
public void inc() { counter++; }
}
public class C extends A {
public void inc() { counter++; }
}
public A[] a = new A[3];
public void test() {
a[0] = new A();
a[1] = new B();
a[2] = new C();
int iter = 100000000;
long start = System.nanoTime();
for(int i = iter; i > 0; i--) {
testUsingInstanceOf(a[i%3]);
}
long end = System.nanoTime();
System.out.println("instanceof: " + iter / ((end - start) / 1000000000.0) + " per second");
start = System.nanoTime();
for(int i = iter; i > 0; i--) {
testUsingException(a[i%3]);
}
end = System.nanoTime();
System.out.println("try{}: " + iter / ((end - start) / 1000000000.0) + " per second");
start = System.nanoTime();
for(int i = iter; i > 0; i--) {
testUsingClassName(a[i%3]);
}
end = System.nanoTime();
System.out.println("classname: " + iter / ((end - start) / 1000000000.0) + " per second");
}
public static void main(String[] args) {
Scratch s = new Scratch();
s.test();
}
public void testUsingInstanceOf(A possiblyB){
if (possiblyB instanceof B){
((B)possiblyB).inc();
}
}
public void testUsingException(A possiblyB){
try{
((B)possiblyB).inc();
} catch(Exception e){
}
}
public void testUsingClassName(A possiblyB){
if (possiblyB.getClass().getName().equals("net.redpoint.utils.Scratch$B")){
((B)possiblyB).inc();
}
}
}
The resulting output:
instanceof: 4.573174070960945E8 per second
try{}: 3.926650051387284E8 per second
classname: 7.689439655530204E7 per second
Test was performed using Oracle JRE7 SE on Windows 8 x64, with Intel i7 sandy bridge CPU.
If the cast can throw an exception, it means that it's doing implicitly what instanceof would do. So, in both cases you are implicitly using reflection, probably in exactly the same way.
The difference is that if the result of instanceof comes back false, no more reflection is happening. If a cast fails and an exception is thrown, you'll have unrolling of the execution stack and, quite possibly, more reflection (for the runtime to determine the correct catch block, based on whether the thrown exception object is an instance of the type to be caught).
The above logic tells me that an instanceof check should be faster. Of course, benchmarking for your particular case would give you the definitive answer.
I don't think you would find one being clearly better than the other.
For instanceof, the work done use memory and cpu time. Creating a exception use memory and cpu time also. Which use less of each, only a well done benchmark would give you that answer.
Coding-wise, I would prefer to see a instanceof rather than casting and having to manage exceptions.

How to pass different enums as argument?

I have some enums, all different, and I want to create a function that can find or not if a string is one of enum variable name (not sure it's really understandable).
enum MYENUM {
ONE,
TWO;
}
enum MYENUM1 {
RED,
GREEN;
}
I want to do this (this is just for the example, my enum are more complicated):
if(isInEnum(MYENUM, "one")) ...
if(isInEnum(MYENUM1, "one")) ...
isinEnum function (the code is bad, it's just for understanding):
boolean isinEnum(enum enumeration, String search) {
for(enum en : enumeration.values()){
if(en.name().equalsIgnoreCase(search)) return true;
}
return false;
}
Is this kind of thing possible?
I think not, according to what I can read on the web, but maybe someone has a solution to do this, instead of making one loop for each enum.
Here is a way using reflection...
public class EnumFinder {
public static <T extends Enum<T>> boolean isInEnum(Class<T> clazz, String name) {
for (T e : clazz.getEnumConstants()) {
if (e.name().equalsIgnoreCase(name)) {
return true;
}
}
return false;
}
public static void main(String[] argv) {
System.out.println(isInEnum(MYENUM.class, "one")); // true
System.out.println(isInEnum(MYENUM1.class, "one")); // false
}
}
Your attempt in your answer was actually very close. The only difference is that Java needs an instance of the defining class in order to answers questions about an unknown type dynamically at runtime.
This may not be the cleanest solution because it uses exceptions in the normal program flow, but it is certainly short, because it avoids the loop:
boolean isinEnum(Class<T> enumClass, String search) {
try {
Enum.valueOf(enumClass, search);
return true;
} catch (IllegalArgumentException iae) {
return false;
}
}
Your question is a bit tough to understand, but I think I get the gist of it.
You might be making things a lot tougher on yourself than necessary.
Take a look at Java's map interface / data structure (in java.util) and see if that moves you closer to your solution:
java.util Interface Map<K,V>
If not, repost with any leg-work you've done and I'll see if I can help ya' further. ;-)

is there a equivalent of StringBuilder for boolean in java?

I want my custom functions to modify / toggle a boolean variable. Let's say that I have code like
if (OK2continue) { findANDclick(new String[]{"id", "menuButton"});}
if (OK2continue) { findANDclick(new String[]{"src", ".*homeicon_calendar.*"}); }
if (OK2continue) { findANDclick(new String[]{"src", ".*cycle_templates.*"});
I want to make sure that the flow of execution stops once any of the findANDclick functions toggles the variable OK2continue
I managed my functions to modify a String variable using StringBuilder.
Can I do the same for boolean type of variable?
I can't say it is equivalent. But using MutableBoolean offers you a mutable boolean wrapper, similar to the concept of StringBuilder a mutable sequence of characters. See this JavaDoc for details.
Push this code into its own method, and use a return:
if (findANDclick(new String[]{"id", "menuButton"})) return;
if (findANDclick(new String[]{"src", ".*homeicon_calendar.*"})) return;
if (findANDclick(new String[]{"src", ".*cycle_templates.*"})) return;
Given that all your method calls are the same, you could also use a loop:
String[][] buttons = {
{"id", "menuButton"},
{"src", ".*homeicon_calendar.*"},
{"src", ".*cycle_templates.*"},
};
for (String[] button: buttons) {
if (findANDclick(button)) return;
}
You might or might not find that more readable.
You need to clarify your reference to your usage of StringBuilder.
Assuming:
You pass reference of the StringBuilder to your method. String is changed in method. If this the case, then see #Gordon Murray Dent's answer.
Your boolean flag is visible in the method but is not passed. A simple Boolean will do.
package sof_6232851;
public class SideEffectingMethod {
static Boolean flag = false;
public static void main(String[] args) {
flag = true;
System.out.format ("flag is %b\n", flag);
clickMe();
System.out.format ("flag is %b\n", flag);
}
/** this method side-effects instance variable flag */
public static void clickMe () {
flag = !flag;
}
}
[edit list item #2 to reply to OP comment]:
Note that #2 is not really recommended. You mention your desire for "readable" code. Side-effecting methods works against that goal.
public class ReturnValuesForFunAndProfit {
public static void main(String[] args) {
presentUI();
}
public static void presentUI() {
if(!clickMe("woof")) return;
if(!clickMe("meow")) return;
if(!clickMe("hello")) return;
}
public static boolean clickMe (String blah) {
// your logic here; this ex. always returns true
return true;
}
}
Well, the concept of StringBuilder is to create a mutable and extendable String wrapper (meaning the string can be extended via append and the like :) ). You'd still have to pass it as a parameter to the method in order to modify it (or use a static var - not recommended).
Since boolean can't be extended, the only similarity would be the parameter to be mutable. So you can use MutableBoolean as Gordon suggested, but you'd still have to pass it.
Another option would be to return a boolean from findANDclick(...) and use the boolean opperators like: findAndClick(...) || findAndClick(...) || findAndClick(...) which would only execute the next findAndClick(...) if the previous returned false.
Since that option is somewhat hard to maintain, especially since you might have side effects in findAndClick(...) as well as being quite static and hard to read if you have more calls in there, you might want to use a list of function objects:
class FindAndClickExecutor {
public FindAndClickExecutor(String[] params) {...}
public boolean findAndClick() {...}
}
List<FindAndClickExecutor> faces = ...; //initialize appropriately
for( FindAndClickExecutor face : faces ) {
boolean ok2continue = face.findAndClick();
if( !ok2continue ) {
break;
}
}
Edit: since there seem to be other methods as well, you might use a more general list:
interface Executor {
boolean execute();
}
class FindAndClickExecutor implements Executor {
public boolean execute() {} // findAndClick code here, set parameters using constructor
}
class FindAndSelectOptionExecutor implements Executor {
public boolean execute() {} // findAndSelectOption code here
}
List<Executor> testCase1Sequence = ...; //initialize test case 1
List<Executor> testCase2Sequence = ...; //initialize test case 2
for( Executor ex : testCase1Sequence ) {
boolean ok2continue = ex.execute();
if( !ok2continue) {
break;
}
}
This example could also be expanded on, e.g. by using a more complex return value containing the continue flag and maybe more data (use interface here as well).
Edit 2: you could also use some scripting to define and the builder pattern to generate the list of executors for each test case.

Categories

Resources