Featured FREE Whitepapers

What's New Here?

software-development-2-logo

An entity modelling strategy for scaling optimistic locking

Introduction Application-level repeatable reads are suitable for preventing lost updates in web conversations. Enabling entity-level optimistic locking is fairly easy. You just have to mark one logical-clock property (usually an integer counter) with the JPA @Version annotation and Hibernate takes care of the rest.           The catch Optimistic locking discards all incoming changes that are relative to an older entity version. But everything has a cost and optimistic locking makes no difference. The optimistic concurrency control mechanism takes an all-or-nothing approach even for non-overlapping changes. If two concurrent transactions are changing distinct entity property subsets then there’s no risk of losing updates. Two concurrent updates, starting from the same entity version are always going to collide. It’s only the first update that’s going to succeed, the second one failing with an optimistic locking exception. This strict policy acts as if all changes are overlapping. For highly concurrent write scenarios, this single-version check strategy can lead to a large number of roll-backed updates. Time for testing Let’s say we have the following Product entity:This entity is updated by three users (e.g. Alice, Bob and Vlad), each one updating a distinct property subset. The following diagram depicts their actions:The SQL DML statement sequence goes like this: #create tables Query:{[create table product (id bigint not null, description varchar(255) not null, likes integer not null, name varchar(255) not null, price numeric(19,2) not null, quantity bigint not null, version integer not null, primary key (id))][]} Query:{[alter table product add constraint UK_jmivyxk9rmgysrmsqw15lqr5b unique (name)][]}#insert product Query:{[insert into product (description, likes, name, price, quantity, version, id) values (?, ?, ?, ?, ?, ?, ?)][Plasma TV,0,TV,199.99,7,0,1]}#Alice selects the product Query:{[select optimistic0_.id as id1_0_0_, optimistic0_.description as descript2_0_0_, optimistic0_.likes as likes3_0_0_, optimistic0_.name as name4_0_0_, optimistic0_.price as price5_0_0_, optimistic0_.quantity as quantity6_0_0_, optimistic0_.version as version7_0_0_ from product optimistic0_ where optimistic0_.id=?][1]} #Bob selects the product Query:{[select optimistic0_.id as id1_0_0_, optimistic0_.description as descript2_0_0_, optimistic0_.likes as likes3_0_0_, optimistic0_.name as name4_0_0_, optimistic0_.price as price5_0_0_, optimistic0_.quantity as quantity6_0_0_, optimistic0_.version as version7_0_0_ from product optimistic0_ where optimistic0_.id=?][1]} #Vlad selects the product Query:{[select optimistic0_.id as id1_0_0_, optimistic0_.description as descript2_0_0_, optimistic0_.likes as likes3_0_0_, optimistic0_.name as name4_0_0_, optimistic0_.price as price5_0_0_, optimistic0_.quantity as quantity6_0_0_, optimistic0_.version as version7_0_0_ from product optimistic0_ where optimistic0_.id=?][1]}#Alice updates the product Query:{[update product set description=?, likes=?, name=?, price=?, quantity=?, version=? where id=? and version=?][Plasma TV,0,TV,199.99,6,1,1,0]}#Bob updates the product Query:{[update product set description=?, likes=?, name=?, price=?, quantity=?, version=? where id=? and version=?][Plasma TV,1,TV,199.99,7,1,1,0]} c.v.h.m.l.c.OptimisticLockingOneRootOneVersionTest - Bob: Optimistic locking failure org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.vladmihalcea.hibernate.masterclass.laboratory.concurrency.OptimisticLockingOneRootOneVersionTest$Product#1]#Vlad updates the product Query:{[update product set description=?, likes=?, name=?, price=?, quantity=?, version=? where id=? and version=?][Plasma HDTV,0,TV,199.99,7,1,1,0]} c.v.h.m.l.c.OptimisticLockingOneRootOneVersionTest - Vlad: Optimistic locking failure org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.vladmihalcea.hibernate.masterclass.laboratory.concurrency.OptimisticLockingOneRootOneVersionTest$Product#1] Because there’s only one entity version, it’s just the first transaction that’s going to succeed. The second and the third updates are discarded since they reference an older entity version. Divide et impera If there are more than one writing patterns, we can divide the original entity into several sub-entities. Instead of only one optimistic locking counter, we now have one distinct counter per each sub-entity. In our example, the quantity can be moved to ProductStock and the likes to ProductLiking.Whenever we change the product quantity, it’s only the ProductStock version that’s going to be checked, so other competing quantity updates are prevented. But now, we can concurrently update both the main entity (e.g. Product) and each individual sub-entity (e.g. ProductStock and ProductLiking):Running the previous test case yields the following output: #create tables Query:{[create table product (id bigint not null, description varchar(255) not null, name varchar(255) not null, price numeric(19,2) not null, version integer not null, primary key (id))][]} Query:{[create table product_liking (likes integer not null, product_id bigint not null, primary key (product_id))][]} Query:{[create table product_stock (quantity bigint not null, product_id bigint not null, primary key (product_id))][]} Query:{[alter table product add constraint UK_jmivyxk9rmgysrmsqw15lqr5b unique (name)][]} Query:{[alter table product_liking add constraint FK_4oiot8iambqw53dwcldltqkco foreign key (product_id) references product][]} Query:{[alter table product_stock add constraint FK_hj4kvinsv4h5gi8xi09xbdl46 foreign key (product_id) references product][]}#insert product Query:{[insert into product (description, name, price, version, id) values (?, ?, ?, ?, ?)][Plasma TV,TV,199.99,0,1]} Query:{[insert into product_liking (likes, product_id) values (?, ?)][0,1]} Query:{[insert into product_stock (quantity, product_id) values (?, ?)][7,1]}#Alice selects the product Query:{[select optimistic0_.id as id1_0_0_, optimistic0_.description as descript2_0_0_, optimistic0_.name as name3_0_0_, optimistic0_.price as price4_0_0_, optimistic0_.version as version5_0_0_ from product optimistic0_ where optimistic0_.id=?][1]} Query:{[select optimistic0_.product_id as product_2_1_0_, optimistic0_.likes as likes1_1_0_ from product_liking optimistic0_ where optimistic0_.product_id=?][1]} Query:{[select optimistic0_.product_id as product_2_2_0_, optimistic0_.quantity as quantity1_2_0_ from product_stock optimistic0_ where optimistic0_.product_id=?][1]}#Bob selects the product Query:{[select optimistic0_.id as id1_0_0_, optimistic0_.description as descript2_0_0_, optimistic0_.name as name3_0_0_, optimistic0_.price as price4_0_0_, optimistic0_.version as version5_0_0_ from product optimistic0_ where optimistic0_.id=?][1]} Query:{[select optimistic0_.product_id as product_2_1_0_, optimistic0_.likes as likes1_1_0_ from product_liking optimistic0_ where optimistic0_.product_id=?][1]} Query:{[select optimistic0_.product_id as product_2_2_0_, optimistic0_.quantity as quantity1_2_0_ from product_stock optimistic0_ where optimistic0_.product_id=?][1]}#Vlad selects the product Query:{[select optimistic0_.id as id1_0_0_, optimistic0_.description as descript2_0_0_, optimistic0_.name as name3_0_0_, optimistic0_.price as price4_0_0_, optimistic0_.version as version5_0_0_ from product optimistic0_ where optimistic0_.id=?][1]} Query:{[select optimistic0_.product_id as product_2_1_0_, optimistic0_.likes as likes1_1_0_ from product_liking optimistic0_ where optimistic0_.product_id=?][1]} Query:{[select optimistic0_.product_id as product_2_2_0_, optimistic0_.quantity as quantity1_2_0_ from product_stock optimistic0_ where optimistic0_.product_id=?][1]}#Alice updates the product Query:{[update product_stock set quantity=? where product_id=?][6,1]}#Bob updates the product Query:{[update product_liking set likes=? where product_id=?][1,1]}#Vlad updates the product Query:{[update product set description=?, name=?, price=?, version=? where id=? and version=?][Plasma HDTV,TV,199.99,1,1,0]} All three concurrent transactions are successful because we no longer have only one logical-clock version but three of them, according to three distinct write responsibilities. Conclusion When designing the persistence domain model, you have to take into consideration both the querying and writing responsibility patterns. Breaking a larger entity into several sub-entities can help you scale updates, while reducing the chance of optimistic locking failures. If you wary of possible performance issues (due to entity state fragmentation) you should then know that Hibernate offers several optimization techniques for overcoming the scattered entity info side-effect. You can always join all sub-entities in a single SQL query, in case you need all entity related data. The second-level caching is also a good solution for fetching sub-entities without hitting the database. Because we split the root entity in several entities, the cache can be better utilized. A stock update is only going to invalidate the associated ProductStock cache entry, without interfering with Product and ProductLiking cache regions.Code available on GitHub.Reference: An entity modelling strategy for scaling optimistic locking from our JCG partner Vlad Mihalcea at the Vlad Mihalcea’s Blog blog....
java-logo

Java Annotations Tutorial – The ULTIMATE Guide (PDF Download)

EDITORIAL NOTE: Annotations in Java are a major feature and every Java developer should know how to utilize them. We have provided an abundance of tutorials here at Java Code Geeks, like Creating Your Own Java Annotations, Java Annotations Tutorial with Custom Annotation and Java Annotations: Explored & Explained. We also featured articles on annotations used in various libraries, including Make your Spring Security @Secured annotations more DRY and Java Annotations & A Real World Spring Example. Now, it is time to gather all the information around Annotations under one reference post for your reading pleasure. Enjoy!Want to master Java Annotations ?Subscribe to our newsletter and download the Java Annotations Ultimate Guide right now! In order to help you master the topic of Annotations, we have compiled a kick-ass guide with all the major features and use cases! Besides studying them online you may download the eBook in PDF format!Email address:Given email address is already subscribed, thank you!Oops. Something went wrong. Please try again later.Please provide a valid email address.Thank you, your sign-up request was successful! Please check your e-mail inbox.Please complete the CAPTCHA.Please fill in the required fields.Table Of Contents1. Why annotations? 2. Introduction 3. Consumers 4. Annotations syntax and annotation elements 5. Where can be used 6. Use cases 7. Built in annotations 8. Java 8 and annotations 9. Custom annotations 10. Retrieving Annotations 11. Inheritance in annotations 12. Known libraries using annotations 13. Summary 14. Download 15. Resources  In this article we are going to explain what Java annotations are, how they work and what can be done using annotations in Java. We will show what annotations come with Java out of the box, also called Built in or Meta annotations and what new features are available in Java 8 related to them. Finally we will implement a custom annotation and a processor application (consumer) that makes use of annotations one using reflection in Java. We will list some very well known and broadly used libraries based on annotations like Junit, JAXB, Spring and Hibernate. At the end of this article you can find a compressed file with all the examples shown in this tutorial. In the implementation of these examples following software versions were used:Eclipse Luna 4.4 JRE Update 8.20 Junit 4 Hibernate 4.3.6 FindBugs 3.0.01. Why annotations? Annotations were introduced in Java in the J2SE update 5 already and the main reason was the need to provide a mechanism that allows programmers to write metadata about their code directly in the code itself. Before annotations, the way programmers were describing their code was not standardized and each developer did it in his own original way: using transient keywords, via comments, with interfaces, etc. This was not a good approach and a decision was taken: a new form of metadata is going to be available in Java, annotations were introduced. Other circumstances help to that decision: At that moment, XML was used as standard code configuration mechanism for different type of applications. This was not the best way to do it because of the decoupling between code and XML (XML is not code!) and the future maintenance of this decoupled applications. There were other reasons like for example the usage of the reserved word “@deprecated” (with small d) in the Javadocs since Java update 4, I am very sure that this was one of the reasons for the current annotations syntax using the “@”. The main Java Specification Requests involved in the annotations design and development are:JSR 175 A metadata facility for the Java programming Language JSR 250 Common Annotations for the Java Platform2. Introduction The best way to explain what an annotation is is the word metadata: data that contains information about itself. Annotations are code metadata; they contain information about the code itself. Annotations can be used within packages, classes, methods, variables and parameters. Since Java 8 annotations can be placed almost in every place of the code, this is called type annotations; we will see this in this tutorial more in detail. The annotated code is not directly affected by their annotations. These only provide information about it to third systems that may use (or not) the annotations for different purposes. Annotations are compiled in the class files and can be retrieved in run time and used with some logical purpose by a consumer or processor. It is also possible to create annotations that are not available at runtime, even is possible to create annotations that are only available in the source and not at compilation time. 3. Consumers It can be difficult to understand what is actually the annotations purpose and what they can be used for, they do not contain any kind of functional logic and they do not affect the code that are annotating, what are they for? The explanation to this is what I call the annotation consumers. These are systems or applications that are making use of the annotated code and executing different actions depending on the annotations information. For example, in the case of the built in annotations (Meta annotations) that come out of the box with the standard Java, the consumer is the Java Virtual Machine (JVM) executing the annotated code. They are other examples that we are going to see later in this tutorial like Junit, where the consumer is the Junit processor reading and analyzing the annotated test classes, and deciding for example, depending on the annotation, in which order the unit tests are going to be executed or what methods are going to be executed before and after every test. We will see this in more detail in the Junit related chapter. Consumers use reflection in Java in order to read and analyze the annotated source code. The main packages used for this purpose are java.lang and java.lang.reflect. We will explain in this tutorial how to create a custom consumer from scratch using reflection. 4. Annotations syntax and annotation elements An annotation is declared using the character ‘@’ as prefix of the annotation name. This indicates the compiler that this element is an annotation. An example: @Annotation public void annotatedMehod() { ... }The annotation above is called “Annotation” and is annotating the method annotatedMethod(). The compiler will take care of it. An annotation has elements in form of key-values. These “elements” are the properties of the annotation. @Annotation( info = "I am an annotation", counter = "55" ) public void annotatedMehod() { ... }If the annotation contains only one element (or if only one element needs to be specified because the rest have default values), we can do something like: @Annotation("I am an annotation") public void annotatedMehod() { ... }As we saw in the first example, if no elements need to be specified, then the parentheses are not needed. Multiple annotations are possible for an element, in this case for a class: @ Annotation (info = "U a u O") @ Annotation2 class AnnotatedClass { ... }Some annotations come out of the box with Java; these are called built in annotations. It is also possible to define your own annotations, these are called custom annotations. We will see these in the next chapters. 5. Where can be used Annotations can be used basically in almost every element of a Java program: classes, fields, methods, packages, variables, etc. Since Java 8 the concept of annotations by type is available. Before Java 8 annotations should be used only in the declarations of the elements listed before. After Java 8 also in declaration of types an annotation can be used. Something like the following is now available: @MyAnnotation String str = "danibuiza"; We will see this mechanism in more detail in the chapter related to Java 8 annotations. 6. Use cases Annotations can be used for many different purposes, the most common ones are:Information for the compiler: Annotations can be used by the compiler to produce warnings or even errors based on different rules. One example of this kind of usage is the Java 8 @FunctionalInterface annotation. This one makes the compiler to validate the annotated class and check if it is a correct functional interface or not. Documentation: Annotations can be used by software applications to measure the quality of the code like FindBugs or PMD do or generate reports automatically like Jenkins, Jira or Teamcity. Code generation: annotations can be used to generate code or XML files automatically using metadata information present in the code. A good example of this is the JAXB library. Runtime processing: Annotations that are examined in runtime can be used for different objectives like unit testing (Junit), dependency injection (Spring), validation, logging (Log4J) ,data access (Hibernate) etc.In this tutorial we will show several possible usages of annotations and we will show how very well known Java libraries are using them 7. Built in annotations The Java language comes with a set of default annotations. In this chapter we are going to explain the most important ones. It is important to mention that this list refers only to the core packages of the Java language and does not include all the packages and libraries available in the standard JRE like JAXB or the Servlet specification Some of the following standard annotations are called Meta annotations; their targets are other annotations and contain information about them:@Retention: This annotation annotates other annotations and it is used to indicate how to store the marked annotation. This annotation is a kind of Meta annotation, since it is marking an annotation and informing about its nature. Possible values are:SOURCE: Indicates that this annotation is ignored by compiler and JVM (no available at run time) and it is only retained in the source. CLASS: Indicates that the annotation is going to be retained by the compiler but ignored by the JVM and because of this, not going to be available at run time. RUNTIME: Means that the annotation is going to be retained by the Java Virtual Machine and can be used in runtime via reflection.We will see several examples of this annotation in this tutorial.@Target: This one restricts the elements that an annotation can be applied to. Only one type is possible. Here is a list of available types:ANNOTATION_TYPE means that the annotation can be applied to other annotation. CONSTRUCTOR can be applied to a constructor. FIELD can be applied to a field or property. LOCAL_VARIABLE can be applied to a local variable. METHOD can be applied to a method-level annotation. PACKAGE can be applied to a package declaration. PARAMETER can be applied to the parameters of a method. TYPE can be applied to any element of a class.@Documented: The annotated elements are going to be documented using the Javadoc tool. Per default annotations are not documented. This annotation can be applied to other annotation. @Inherited: By default annotations are not inherited by subclasses. This annotation marks an annotation to automatic inherit to all subclasses extending the annotated class. This annotation can be applied to class elements. @Deprecated: Indicates that the annotated element should not be used. This annotation gets the compiler to generate a warning message. Can be applied to methods, classes and fields. An explanation about why this element is deprecated and alternative usages should be provided when using this annotation. @SuppressWarnings: Indicates the compiler not to produce warnings for an specific reason or reasons. For example if we do not want to get warnings because of unused private methods we can write something like:@SuppressWarnings( "unused") private String myNotUsedMethod(){ ... }Normally the compiler would produce a warning if this method is not used; using this annotation prevents that behavior. This annotation expects one or more parameters with the warnings categories to avoid.@Override: Indicates the compiler that the element is overriding an element of the super class. This annotation is not mandatory to use when overriding elements but it helps the compiler to generate errors when the overriding is not done correctly, for example if the sub class method parameters are different than the super class ones, or if the return type does not match. @SafeVarargs: Asserts that the code of the method or constructor does not perform unsafe operations on its arguments. Future versions of the Java language will make the compiler to produce an error at compilation time in case of potential unsafe operations while using this annotation. For more information about this one one http://docs.oracle.com/javase/7/docs/api/java/lang/SafeVarargs.html8. Java 8 and annotations Java 8 comes out with several advantages. Also the annotations framework is improved. In this chapter we are going to explain and provide examples of the 3 main topics introduced in the eighth Java update: the @Repeatable annotation, the introduction of type annotation declarations and the functional interface annotation @FunctionalInterface (used in combination with Lambdas).@Repeatable: indicates that an annotation annotated with this one can be applied more than once to the same element declaration.Here is an example of usage. First of all we create a container for the annotation that is going to be repeated or that can be repeated: /** * Container for the {@link CanBeRepeated} Annotation containing a list of values */ @Retention( RetentionPolicy.RUNTIME ) @Target( ElementType.TYPE_USE ) public @interface RepeatedValues { CanBeRepeated[] value(); }Afterwards, we create the annotation itself and we mark it with the Meta annotation @Repeatable: @Retention( RetentionPolicy.RUNTIME ) @Target( ElementType.TYPE_USE ) @Repeatable( RepeatedValues.class ) public @interface CanBeRepeated {String value(); }Finally we can see how to use it (repeatedly) in a given class: @CanBeRepeated( "the color is green" ) @CanBeRepeated( "the color is red" ) @CanBeRepeated( "the color is blue" ) public class RepeatableAnnotated {}If we would try to do the same with a non repeatable annotation: @Retention( RetentionPolicy.RUNTIME ) @Target( ElementType.TYPE_USE ) public @interface CannotBeRepeated {String value(); }@CannotBeRepeated( "info" ) /* * if we try repeat the annotation we will get an error: Duplicate annotation of non-repeatable type * * @CannotBeRepeated. Only annotation types marked * * @Repeatable can be used multiple times at one target. */ // @CannotBeRepeated( "more info" ) public class RepeatableAnnotatedWrong {}We would get an error from the compiler like: Duplicate annotation of non-repeatable typeSince Java 8 is also possible to use annotations within types. That is anywhere you can use a type, including the new operator, castings, implements and throws clauses. Type Annotations allow improved analysis of Java code and can ensure even stronger type checking. The following examples clarify this point:@SuppressWarnings( "unused" ) public static void main( String[] args ) { // type def @TypeAnnotated String cannotBeEmpty = null;// type List<@TypeAnnotated String> myList = new ArrayList<String>();// values String myString = new @TypeAnnotated String( "this is annotated in java 8" );}// in method params public void methodAnnotated( @TypeAnnotated int parameter ) { System.out.println( "do nothing" ); }All this was not possible until Java 8.@FunctionalInterface: this annotation indicates that the element annotated is going to be a functional interface. A functional interface is an interface that has just one abstract method (not a default one). The compiler will handle the annotated element as a functional interface and will produce an error if the element does not comply with the needed requirements. Here is an example of functional interface annotation:// implementing its methods @SuppressWarnings( "unused" ) MyCustomInterface myFuncInterface = new MyCustomInterface() {@Override public int doSomething( int param ) { return param * 10; } };// using lambdas @SuppressWarnings( "unused" ) MyCustomInterface myFuncInterfaceLambdas = ( x ) -> ( x * 10 ); }@FunctionalInterface interface MyCustomInterface { /* * more abstract methods will cause the interface not to be a valid functional interface and * the compiler will thrown an error:Invalid '@FunctionalInterface' annotation; * FunctionalInterfaceAnnotation.MyCustomInterface is not a functional interface */ // boolean isFunctionalInterface();int doSomething( int param ); }This annotation can be applied to classes, interfaces, enums and annotations and it is retained by the JVM and available in Run time. Here is its declaration: @Documented @Retention(value=RUNTIME) @Target(value=TYPE) public @interface FunctionalInterface For more information about this annotation http://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html. 9. Custom annotations As we mentioned several times in this tutorial, it is possible to define and implement custom annotations. In this chapter we are going to show how to do this. First of all, define the new annotation: public @interface CustomAnnotationClass This creates a new type of annotation called CustomAnnotationClass. The special word used for this purpose is @interface, this indicates the definition of a custom annotation. After this, you need to define a couple of mandatory attributes for this annotation, the retention policy and the target. There are other attributes that can be defined here, but these are the most common and important ones. These are declared in form of annotations of an annotation and were described in the chapter “Built in annotations” since they are annotations that came out of the box with Java. So we define these properties for our new custom annotation: @Retention( RetentionPolicy.RUNTIME ) @Target( ElementType.TYPE ) public @interface CustomAnnotationClass implements CustomAnnotationMethodWith the retention policy RUNTIME we indicate to the compiler that this annotation should be retained by the JVM and can be analyzed in runtime using reflection. With the element type TYPE we are indicating that this annotation can be applied to any element of a class. Afterwards we define a couple of properties for this annotation: @Retention( RetentionPolicy.RUNTIME ) @Target( ElementType.TYPE ) public @interface CustomAnnotationClass {public String author() default "danibuiza";public String date();}Above we have just defined the property author, with the default value “danibuiza” and the property date, without default value. We should mention that all method declarations cannot have parameters and are not allowed to have a thrown clause. The return types are restricted to String, Class, enums, annotations and arrays of the types mentioned before. Now we can use our fresh created custom annotation in the following way: @CustomAnnotationClass( date = "2014-05-05" ) public class AnnotatedClass { ... }In a similar way we can create an annotation to be used in method declarations, using the target METHOD: @Retention( RetentionPolicy.RUNTIME ) @Target( ElementType.METHOD ) public @interface CustomAnnotationMethod { public String author() default "danibuiza";public String date();public String description();}This one can be used in a method declaration like: @CustomAnnotationMethod( date = "2014-06-05", description = "annotated method" ) public String annotatedMethod() { return "nothing niente"; }@CustomAnnotationMethod( author = "friend of mine", date = "2014-06-05", description = "annotated method" ) public String annotatedMethodFromAFriend() { return "nothing niente"; }There are many other properties that can be used with custom annotations, but target and retention policy are the most important ones. 10. Retrieving Annotations The Java reflection API contains several methods that can be used to retrieve in runtime annotations from classes, methods and other elements. The interface that contains all these methods is AnnotatedElement and the most important ones are:getAnnotations(): Returns all annotations for the given element, also the ones that are not explicitly defined in the element definition. isAnnotationPresent(annotation): Checks if the passed annotation in available or not in the current element. getAnnotation(class): Retrieves an specific annotation passed as parameter. Returns null if this annotation is not present for the given element.This class is implementing by java.lang.Class, java.lang.reflect.Method and java.lang.reflect.Field among others, so can be used basically with any kind of Java element. Now we are going to see an example of how to read the annotations present in a class or method using the methods listed above: We write a program that tries to read all the annotations present in a class and its methods (we use for this example the classes defined before):public static void main( String[] args ) throws Exception {Class<AnnotatedClass> object = AnnotatedClass.class; // Retrieve all annotations from the class Annotation[] annotations = object.getAnnotations(); for( Annotation annotation : annotations ) { System.out.println( annotation ); }// Checks if an annotation is present if( object.isAnnotationPresent( CustomAnnotationClass.class ) ) {// Gets the desired annotation Annotation annotation = object.getAnnotation( CustomAnnotationClass.class );System.out.println( annotation );} // the same for all methods of the class for( Method method : object.getDeclaredMethods() ) {if( method.isAnnotationPresent( CustomAnnotationMethod.class ) ) {Annotation annotation = method.getAnnotation( CustomAnnotationMethod.class );System.out.println( annotation );}} }The output of this program would be: @com.danibuiza.javacodegeeks.customannotations.CustomAnnotationClass(getInfo=Info, author=danibuiza, date=2014-05-05)@com.danibuiza.javacodegeeks.customannotations.CustomAnnotationClass(getInfo=Info, author=danibuiza, date=2014-05-05)@com.danibuiza.javacodegeeks.customannotations.CustomAnnotationMethod(author=friend of mine, date=2014-06-05, description=annotated method) @com.danibuiza.javacodegeeks.customannotations.CustomAnnotationMethod(author=danibuiza, date=2014-06-05, description=annotated method)In the program above we can see the usage of the method getAnnotations() in order to retrieve all annotations for a given object (a method or a class). We also showed how to check if an specific annotation is present and to retrieve it in positive case using the methods isAnnotationPresent() and getAnnotation(). 11. Inheritance in annotations Annotations can use inheritance in Java. This inheritance has nothing or almost nothing in common with what we know by inheritance in an object oriented programming language where an inherited class inherits methods, elements and behaviors from his super class or interface. If an annotation is marked as inherited in Java, using the reserved annotation @Inherited, indicates that the class that is annotated will pass this annotation to its subclasses automatically without need to declare the annotation in the sub classes. By default, a class extending a super class does not inherit its annotations. This is completely in line with the objective of annotations, which is to provide information about the code that they are annotating and not to modify its behavior. We are going to see this using an example that makes thing clearer. First, we define a custom annotation that uses inheritance automatically @Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface InheritedAnnotation {}We have a super class called AnnotatedSuperClass with the @InheritedAnnotation annotation declared above: @InheritedAnnotation public class AnnotatedSuperClass {public void oneMethod() {}}A subclass extending this one: public class AnnotatedSubClass extends AnnotatedSuperClass {@Override public void oneMethod(){ } }The sub class AnnotatedSubClass shown above will automatically inherit the annotation @InheritedAnnotation. We can see this using the following test with the method isAnnotationPresent() present in the every class:System.out.println( "is true: " + AnnotatedSuperClass.class.isAnnotationPresent( InheritedAnnotation.class ) ); System.out.println( "is true: " + AnnotatedSubClass.class.isAnnotationPresent( InheritedAnnotation.class ) );The output to these lines is: is true: true is true: trueWe can see how the annotation is inherited by the sub class automatically with no need of declaring it. If we try to use this kind of annotation in an interface like this: @InheritedAnnotation public interface AnnotatedInterface {public void oneMethod();}An implementation for it: public class AnnotatedImplementedClass implements AnnotatedInterface {@Override public void oneMethod() {}}And we check the result of the annotation inheritance using the isAnnotationPresent() method:System.out.println( "is true: " + AnnotatedInterface.class.isAnnotationPresent( InheritedAnnotation.class ) ); System.out.println( "is true: " + AnnotatedImplementedClass.class.isAnnotationPresent( InheritedAnnotation.class ) );The result of the previous program will be is true: true is true: falseThis shows how inheritance works in relation with annotations and interfaces: it is just ignored. The implementing class do not inherit the annotation although it is an inherit annotation; it only applies to classes like in the case of the AnnotatedSubClass class above. The @Inherited annotation is only applicable to classes and annotations present in the interfaces have no effect in the implementing classes. The same happens with methods, variables, packages, etc. Only classes can be used in conjunction with this annotation. A very good explanation can be found in the Javadoc of the @Inherited annotation: http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Inherited.html. Annotations cannot inherit from other annotations; if you try to do this you will get a compilation error: Annotation type declaration cannot have explicit superinterfaces 12. Known libraries using annotations In this chapter we are going to show how very well known Java libraries make usage of annotations. Several libraries like JAXB, Spring Framework, Findbugs, Log4j, Hibernate, and Junit… (The list can be infinite) use them for several different things like code quality analysis, unit testing, XML parsing, dependency injection and many others. In this tutorial we are going to show some of these use cases: 12.1. Junit This framework is used for unit testing in Java. Since its version 4 annotations are widely used and are one of the pillars of Junit design. Basically the Junit processor reads using reflection the classes and suites that may contain unit tests and execute them depending on the annotations found at the beginning of each method or class. There are Junit annotations that modify the way a test is executed; others are used exactly for test execution, for prevention of execution, changing order of execution, etc. The list of possible annotations is very large but we are going to see here the most important ones:@Test: This annotation indicates Junit that the annotated method has to be executed as unit test. It is applicable for methods only (using the target element type METHOD) and is retained in runtime by the Java Virtual Machine (using the retention policy RUNTIME).@Test public void testMe() { //test assertions assertEquals(1,1); } In the example above we can see how to use this kind of annotation in Junit.@Before: the before annotation is used to indicate Junit that the marked method should be executed before every test. This is very useful for set up methods where test context are initialized. Is applicable to methods only:@Before public void setUp() { // initializing variables count = 0; init();}@After: This annotation is used to indicate the Junit processor that all marked methods should be executed after every unit test. This annotation is normally used for destroying, closing or finalizing methods where resources are cleared and reset:@After public void destroy() { // closing input stream stream.close(); }@Ignore: This one indicates Junit that the methods marked should not be executed as unit test. Even if they are annotated as test. They should be just ignored:@Ignore @Test public void donotTestMe() { count = -22; System.out.println( "donotTestMe(): " + count ); } This method should be used during development and debugging phases but it is not common to leave ignored tests once the code is ready to go to production.@FixMethodOrder: Indicates what order of execution should be used, normally the Junit processor takes care of this and the default execution order is completely unknown and random for the programmer. This annotation is not really recommended since Junit methods and tests should be completely independent from each other and the order of execution should not affect the results. However, there are cases and scenarios where the order of unit tests should follow some rules where this annotation may be very useful.@FixMethodOrder( MethodSorters.NAME_ASCENDING ) public class JunitAnnotated There are other test suites and libraries making use of annotations like Mockito or JMock where annotations are used for the creation of test objects and methods expectations. For a complete list of available annotations in Junit https://github.com/junit-team/junit/wiki/Getting-started 12.2. Hibernate ORM Hibernate is probably the most used library for object relational mapping in Java. it provides a framework for mapping object model and relational databases. It makes use of annotations as part of its design. In this chapter we are going to see a couple of annotations provided by Hibernate and to explain how its processor handles them. The snippet bellow has the annotations @Entity and @Table. These are used to indicate the consumer (the Hibernate processor) that the annotated class is an entity bean and indicates what SQL table should be used for the objects of this class. Actually this annotation just explains which one is the primary table; there are annotations for the secondary as well. @Entity @Table( name = "hibernate_annotated" ) public class HibernateAnnotated In the following piece of code we show how to indicate the Hibernate processor that the marked element is a table id with the name “id” and that it should be auto generated (the typical auto increment SQL ids):@Id @GeneratedValue @Column( name = "id" ) private int id;In order to specify a standard SQL table column we can write something like this before an element:@Column( name = "description" ) private String description; This indicates that the marked element is a column with the name “description” in the table specified at the beginning of the class. These annotations belong to the http://docs.oracle.com/javaee/6/api/javax/persistence/package-summary.html package from the Java Enterprise Edition and basically it covers all the available annotations that hibernate uses (or at least the most common ones). 12.3. Spring MVC Spring is a framework widely used for implementing Java Enterprise applications. One of its most important features is the usage of dependency injection in Java programs. Spring uses annotations as an alternative to XML based configuration (the first Spring versions used only XML based configurations). Currently both options are available; you can configure your projects using annotations and XML configuration files. In my opinion both approaches have benefits and inconveniences. Here we are just going to show two of the multiple annotations available in Spring. In the following example: @Component public class DependencyInjectionAnnotation {private String description;public String getDescription() { return description; }@Autowired public void setDescription( String description ) { this.description = description; }} In the snippet above we can find two kinds of annotations applied to the whole class and to a method respectively:@Component: Indicates that the element marked by this annotation, in this case a class, is a candidate for auto detection. This means that the annotated class may be a bean and should be taken into consideration by the Spring container. @Autowired: The Spring container will try to perform byType auto wiring (this is a kind of property matching using the elements type) on this setter method. It can be applied to constructor and properties as well and the actions the Spring container takes in these cases are different.For more information about dependency injection and the Spring framework in general please visit: http://projects.spring.io/spring-framework/. 12.4. Findbugs This library is used in order to measure the quality of the code and provide a list of possibilities to improve it. It checks the code against a list of predefined (or customized) quality violations. Findbugs provide a list of annotations that allow programmers to change its default behavior. Findbugs mainly reads the code (and its contained annotations) using reflection and decides what actions should be taken depending on them. One example is the annotation edu.umd.cs.findbugs.annotations.SuppressFBWarnings that expects a violation key as parameter (one or more values as parameter have to be provided, no need for the key, since it is the default “value” key). It is very similar to the java.lang.SuppressWarnings one. It is used to indicate the Findbugs processor to ignore specific violations while executing the code analysis. Here is an example of use: @SuppressFBWarnings( "HE_EQUALS_USE_HASHCODE" ) public class FindBugsAnnotated {@Override public boolean equals( Object arg0 ) { return super.equals( arg0 ); }} The class above overrides the equals() method of the Object class but does not do the same with the hashCode() method. This is normally a problem because hashCode() and equals() should be override both of them in order not to have problems while using the element as key in a HashMap for example. So Findbugs will create an error entry in the violations report for it. If the annotation @SuppressFBWarnings with the value HE_EQUALS_USE_HASHCODE would not be there the FindBugs processor would throw an error of the type:Bug: com.danibuiza.javacodegeeks.findbugsannotations.FindBugsAnnotated defines equals and uses Object.hashCode() Bug: com.danibuiza.javacodegeeks.findbugsannotations.FindBugsAnnotated defines equals and uses Object.hashCode()This class overrides equals(Object), but does not override hashCode(), and inherits the implementation of hashCode() from java.lang.Object (which returns the identity hash code, an arbitrary value assigned to the object by the VM). Therefore, the class is very likely to violate the invariant that equal objects must have equal hashcodes. If you don’t think instances of this class will ever be inserted into a HashMap/HashTable, the recommended hashCode implementation to use is:public int hashCode() { assert false : "hashCode not designed"; return 42; // any arbitrary constant will do }Rank: Troubling (14), confidence: High Pattern: HE_EQUALS_USE_HASHCODE Type: HE, Category: BAD_PRACTICE (Bad practice) This error contains an explanation of the problem and hints about how to solve it. In this case the solution is basically to implement the hashCode() method as well. For a complete list of all FindBugs violations that can be used as value in the SuppressFBWarnings annotation http://findbugs.sourceforge.net/bugDescriptions.html. 12.5. JAXB JAXB is a library used for conversion and mapping of XML files into Java objects and vice versa. Actually this library comes with the standard JRE and there is no need to download it or configure it in any way. It can be used directly by importing the classes in the package javax.xml.bind.annotation in your applications. JAXB uses annotations to inform its processor (or the JVM) of the XML to code (and viceversa) conversion. For example there are annotations used to indicate XML nodes in the code, XML attributes, values, etc. We are going to see an example: First of all, we declare a class indicating that it should be a node in the XML: import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlType( propOrder = { "brand", "model", "year", "km" } ) @XmlRootElement( name = "Car" ) class Car ... The annotations used here are @XmlType and @XmlRootElement. They inform the JAXB processor that the class Car is going to be a node in the XML produced in the result of the conversion. The @XmlType indicates the order of the properties in the resultant XML. JAXB will perform the proper actions based on these annotations. Apart of a setters and getters for the desired properties, nothing else is needed in this class in order to make it available for conversion. Now we need a consumer program that executes the conversion to XML:Car car = new Car(); car.setBrand( "Mercedes" ); car.setModel( "SLK" ); car.setYear( 2011 ); car.setKm( 15000 );Car carVW = new Car(); carVW.setBrand( "VW" ); carVW.setModel( "Touran" ); carVW.setYear( 2005 ); carVW.setKm( 150000 );/* init jaxb marshaler */ JAXBContext jaxbContext = JAXBContext.newInstance( Car.class ); Marshaller jaxbMarshaller = jaxbContext.createMarshaller();/* set this flag to true to format the output */ jaxbMarshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );/* marshaling of java objects in xml (output to standard output) */ jaxbMarshaller.marshal( car, System.out ); jaxbMarshaller.marshal( carVW, System.out );The output of this program will be something like: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Car> <brand>Mercedes</brand> <model>SLK</model> <year>2011</year> <km>15000</km> </Car> <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Car> <brand>VW</brand> <model>Touran</model> <year>2005</year> <km>150000</km> </Car> There is a list of annotations that can be used in JAXB for XML to Java conversion. More information can be found in https://jaxb.java.net/ 13. Summary In this article we explained that annotations in Java are a very important feature available since the update 5, and we listed several uses cases where they can be used.  Basically annotations are metadata that contain information about the marked code. They do not change or affect the code by any meaning and they can be used by 3rd applications called consumers in order to analyze the code using reflection. We listed the built in annotations that are available per default in Java, some of them also called meta annotations like @Target or @Retention, or others like @Override or @SuppressWarnings, and the new features coming out in Java 8 related to annotations like the @Repeteable annotation, the @FunctionalInterface annotation and the annotations by type. We also shown a couple of code examples where annotations were used in combination with reflection and we mentioned and described several real life libraries that are doing extensive use of annotations in Java like Junit, Spring or Hibernate. Annotations are a very powerful mechanism in Java to analyze the Meta data of any kind of programs and can be applicable in different scopes like validation, dependency injection or unit testing. 14. Download This was a tutorial on Java annotations. Download You can download the full source code of this tutorial here: customAnnotations 15. Resources Here is a list of very useful resources related to Java annotations:Official Java annotations site: http://docs.oracle.com/javase/tutorial/java/annotations/ Wikipedia article about annotations in Java: http://en.wikipedia.org/wiki/Java_annotation Java Specification Request 250: http://en.wikipedia.org/wiki/JSR_250 Annotations white paper from Oracle: http://www.oracle.com/technetwork/articles/hunter-meta-096020.html Annotations API: http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/package-summary.html...
neo4j-logo

Using the Neo4j browser with Embedded Neo4j

There are times when you have an application using Neo4j in embedded mode but also need to play around with the graph using the Neo4j web browser. Since the database can be accessed from at most one process at a time, trying to start up the Neo4j server when your embedded Neo4j  application is running won’t work. The WrappingNeoServerBootstrapper, although deprecated, comes to the rescue. Here’s how to set it up.           1. Make sure you have these maven dependencies <dependency> <groupId>org.neo4j</groupId> <artifactId>neo4j</artifactId> <version>2.1.5</version> </dependency> <dependency> <groupId>org.neo4j.app</groupId> <artifactId>neo4j-server</artifactId> <version>2.1.5</version> </dependency> <dependency> <groupId>org.neo4j.app</groupId> <artifactId>neo4j-server</artifactId> <version>2.1.5</version> <classifier>static-web</classifier> </dependency> 2. Start the WrappingNeoServerBootstrapperpublic static void connectAndStartBootstrapper() { WrappingNeoServerBootstrapper neoServerBootstrapper; GraphDatabaseService db = new GraphDatabaseFactory() .newEmbeddedDatabaseBuilder("/path/to/db").newGraphDatabase(); registerShutdownHook(db); try { GraphDatabaseAPI api = (GraphDatabaseAPI) db; ServerConfigurator config = new ServerConfigurator(api); config.configuration() .addProperty(Configurator.WEBSERVER_ADDRESS_PROPERTY_KEY, "127.0.0.1"); config.configuration() .addProperty(Configurator.WEBSERVER_PORT_PROPERTY_KEY, "7575");neoServerBootstrapper = new WrappingNeoServerBootstrapper(api, config); neoServerBootstrapper.start(); catch(Exception e) { //handle appropriately } }Two things happen here- the GraphDatabaseService is ready to use in embedded mode, and the Neo4j web browser is available for use on http://127.0.0.1:7575/ You need not start them together but instead start and stop the WrappingNeoServerBootstrapper on demand, you just need to have a handle to the GraphDatabaseService. Again, note that the WrappingNeoServerBootstrapper is deprecated. At the time of writing, this code works on 2.1.5 but does not offer any guarantees for future releases of Neo4j.Reference: Using the Neo4j browser with Embedded Neo4j from our JCG partner Luanne Misquitta at the Thought Bytes blog....
java-logo

Five Reasons Why You Should Keep Your Package Dependencies Cycle Free

If you are so unlucky to work with me in a project, you will suffer from the rule that all package dependencies must be cycle free. I will not only require this, but I will also create a unit test ensuring it using Degraph. Here are the reasons why I think a cycle free package structure is beneficial for a project.              Helpful abstractions: If you implement stuff without thinking to much about dependencies you end up with cyclic dependencies almost for sure. In order to break those cycles you often have to introduce new abstractions in the form of interfaces. These interfaces often turnout to create a cleaner abstraction of what is going on in the application than the direct dependency that was there before.For example consider two packages Something and Other that depend on each other. As it is described, there is no way to tell why they depend on each other. But in order to break one of the dependencies you might decide to introduce an interface. The name of that interface might include valuable additional information about the relationship of the two. Imagine the interface ends up being named SomethingDeletionListener and located in Somehting and implemented in Other. This already tells you something about the relationship of the two packages, doesn’t it? Clean Orthogonal Package Structure: Whenever you organize something in a tree like structure you probably want an orthogonal structure in that tree. This means on all subbranches of a branch are elements of single categorization. A good example is Customer, Order, Wishlist a different, also good example is UserInterface, Persistence, Domain. These kinds of structures gives a clear indication where a class belongs. If you mix the two approaches you end up with something like Customer, Order, Persistence. In such a structure it is not at all clear where classes for the persistence of customers belong. The result is a mess, which typically results in cycles in the dependencies, since a question like should Customer depend on Persistence or the other way around doesn’t even make sense. Enables reuse: Ever tried to reuse a package or even just a single class from a project that doesn’t care about dependencies? I tried. In 9 out of 10 cases I had two choices: Either take the complete project (not really an option), or do some heavy refactoring of the class before it even compiles without all the other stuff in the project. On the other hand in projects where package dependencies form a nice directed acyclic graph, it is perfectly clear what has to go with the class. Also the stuff people are interested in reusing is typically close to the leaves of the graph and can be extracted on it’s own or with very few dependencies. Enables partial rewrites: Sometimes an idea once considered great turns out to be a really bad one. Sometimes it is so bad, you want to redo it. Acyclic dependencies limit the amount of code affected by the change. With cyclic dependencies often the complete application is at least in danger of being affected. Independent deployment: On the other hand, sometimes ideas actually turn out to be great. Maybe so great that they get used so heavily, that you need to scale it up and deploy it on three additional servers on its own, to handle the heavy load. Good luck in splitting your application in two or more parts that can be deployed separately when you have tangles between the packages. With a cycle free structure, the places where you can cut should be rather obvious.Reference: Five Reasons Why You Should Keep Your Package Dependencies Cycle Free from our JCG partner Jens Schauder at the Schauderhaft blog....
java-interview-questions-answers

Batching (collapsing) requests in Hystrix

Hystrix has an advanced feature of collapsing (or batching) requests. If two or more commands run similar request at the same time, Hystrix can combine them together, run one batched request and dispatch split results back to all commands. Let’s first see how Hystrix works without collapsing. Imagine we have a service that looks up StockPriceof a given Ticker:             import lombok.Value; import java.math.BigDecimal; import java.time.Instant;@Value class Ticker { String symbol; }@Value class StockPrice { BigDecimal price; Instant effectiveTime; }interface StockPriceGateway {default StockPrice load(Ticker stock) { final Set<Ticker> oneTicker = Collections.singleton(stock); return loadAll(oneTicker).get(stock); }ImmutableMap<Ticker, StockPrice> loadAll(Set<Ticker> tickers); }Core implementation of StockPriceGateway must provide loadAll() batch method while load() method is implemented for our convenience. So our gateway is capable of loading multiple prices in one batch (e.g. to reduce latency or network protocol overhead), but at the moment we are not using this feature, always loading price of one stock at a time: class StockPriceCommand extends HystrixCommand<StockPrice> {private final StockPriceGateway gateway; private final Ticker stock;StockPriceCommand(StockPriceGateway gateway, Ticker stock) { super(HystrixCommandGroupKey.Factory.asKey("Stock")); this.gateway = gateway; this.stock = stock; }@Override protected StockPrice run() throws Exception { return gateway.load(stock); } }Such command will always call StockPriceGateway.load() for each and every Ticker, as illustrated by the following tests: class StockPriceCommandTest extends Specification {def gateway = Mock(StockPriceGateway)def 'should fetch price from external service'() { given: gateway.load(TickerExamples.any()) >> StockPriceExamples.any() def command = new StockPriceCommand(gateway, TickerExamples.any())when: def price = command.execute()then: price == StockPriceExamples.any() }def 'should call gateway exactly once when running Hystrix command'() { given: def command = new StockPriceCommand(gateway, TickerExamples.any())when: command.execute()then: 1 * gateway.load(TickerExamples.any()) }def 'should call gateway twice when command executed two times'() { given: def commandOne = new StockPriceCommand(gateway, TickerExamples.any()) def commandTwo = new StockPriceCommand(gateway, TickerExamples.any())when: commandOne.execute() commandTwo.execute()then: 2 * gateway.load(TickerExamples.any()) }def 'should call gateway twice even when executed in parallel'() { given: def commandOne = new StockPriceCommand(gateway, TickerExamples.any()) def commandTwo = new StockPriceCommand(gateway, TickerExamples.any())when: Future<StockPrice> futureOne = commandOne.queue() Future<StockPrice> futureTwo = commandTwo.queue()and: futureOne.get() futureTwo.get()then: 2 * gateway.load(TickerExamples.any()) }}If you don’t know Hystrix, by wrapping an external call in a command you gain a lot of features like timeouts, circuit breakers, etc. But this is not the focus of this article. Look at last two tests: when asking for price of arbitrary ticker twice, sequentially or in parallel (queue()), our external gateway is also called twice. Last test is especially interesting – we ask for the same ticker at almost the same time, but Hystrix can’t figure that out. These two commands are fully independent, will be executed in different threads and don’t know anything about each other – even though they run at almost the same time. Collapsing is all about finding such similar requests and combining them. Batching (I will use this term interchangeably with collapsing) doesn’t happen automatically and requires a bit of coding. But first let’s see how it behaves: def 'should collapse two commands executed concurrently for the same stock ticker'() { given: def anyTicker = TickerExamples.any() def tickers = [anyTicker] as Setand: def commandOne = new StockTickerPriceCollapsedCommand(gateway, anyTicker) def commandTwo = new StockTickerPriceCollapsedCommand(gateway, anyTicker)when: Future<StockPrice> futureOne = commandOne.queue() Future<StockPrice> futureTwo = commandTwo.queue()and: futureOne.get() futureTwo.get()then: 0 * gateway.load(_) 1 * gateway.loadAll(tickers) >> ImmutableMap.of(anyTicker, StockPriceExamples.any()) }def 'should collapse two commands executed concurrently for the different stock tickers'() { given: def anyTicker = TickerExamples.any() def otherTicker = TickerExamples.other() def tickers = [anyTicker, otherTicker] as Setand: def commandOne = new StockTickerPriceCollapsedCommand(gateway, anyTicker) def commandTwo = new StockTickerPriceCollapsedCommand(gateway, otherTicker)when: Future<StockPrice> futureOne = commandOne.queue() Future<StockPrice> futureTwo = commandTwo.queue()and: futureOne.get() futureTwo.get()then: 1 * gateway.loadAll(tickers) >> ImmutableMap.of( anyTicker, StockPriceExamples.any(), otherTicker, StockPriceExamples.other()) }def 'should correctly map collapsed response into individual requests'() { given: def anyTicker = TickerExamples.any() def otherTicker = TickerExamples.other() def tickers = [anyTicker, otherTicker] as Set gateway.loadAll(tickers) >> ImmutableMap.of( anyTicker, StockPriceExamples.any(), otherTicker, StockPriceExamples.other())and: def commandOne = new StockTickerPriceCollapsedCommand(gateway, anyTicker) def commandTwo = new StockTickerPriceCollapsedCommand(gateway, otherTicker)when: Future<StockPrice> futureOne = commandOne.queue() Future<StockPrice> futureTwo = commandTwo.queue()and: def anyPrice = futureOne.get() def otherPrice = futureTwo.get()then: anyPrice == StockPriceExamples.any() otherPrice == StockPriceExamples.other() }First test proves that instead of calling load() twice we barely called loadAll() once. Also notice that since we asked for the same Ticker (from two different threads), loadAll() asks for only one ticker. Second test shows two concurrent requests for two different tickers being collapsed into one batch call. Third test makes sure we still get proper responses to each individual request. Instead of extending HystrixCommand we must extend more complexHystrixCollapser. Now it’s time to see StockTickerPriceCollapsedCommand implementation, that seamlessly replaced StockPriceCommand: class StockTickerPriceCollapsedCommand extends HystrixCollapser<ImmutableMap<Ticker, StockPrice>, StockPrice, Ticker> {private final StockPriceGateway gateway; private final Ticker stock;StockTickerPriceCollapsedCommand(StockPriceGateway gateway, Ticker stock) { super(HystrixCollapser.Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("Stock")) .andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter().withTimerDelayInMilliseconds(100))); this.gateway = gateway; this.stock = stock; }@Override public Ticker getRequestArgument() { return stock; }@Override protected HystrixCommand<ImmutableMap<Ticker, StockPrice>> createCommand(Collection<CollapsedRequest<StockPrice, Ticker>> collapsedRequests) { final Set<Ticker> stocks = collapsedRequests.stream() .map(CollapsedRequest::getArgument) .collect(toSet()); return new StockPricesBatchCommand(gateway, stocks); }@Override protected void mapResponseToRequests(ImmutableMap<Ticker, StockPrice> batchResponse, Collection<CollapsedRequest<StockPrice, Ticker>> collapsedRequests) { collapsedRequests.forEach(request -> { final Ticker ticker = request.getArgument(); final StockPrice price = batchResponse.get(ticker); request.setResponse(price); }); }}A lot is going on here, so let’s review StockTickerPriceCollapsedCommand step by step. First three generic types:BatchReturnType (ImmutableMap<Ticker, StockPrice> in our example) is the type of batched command response. As you will see later, collapser turns multiple small commands into a batch command. This is the type of that batch command’s response. Notice that it’s the same as StockPriceGateway.loadAll() type). ResponseType (StockPrice) is the type of each individual command being collapsed. In our case we are collapsing HystrixCommand<StockPrice>. Later we will split value of BatchReturnType into multiple StockPrice. RequestArgumentType (Ticker) is the input of each individual command we are about to collapse (batch). When multiple commands are batched together, we are eventually replacing all of them with one batched command. This command should receive all individual requests in order to perform one batch request.withTimerDelayInMilliseconds(100) will be explained soon. createCommand() creates a batch command. This command should replace all individual commands and perform batched logic. In our case instead of multiple individualload() calls we just make one: class StockPricesBatchCommand extends HystrixCommand<ImmutableMap<Ticker, StockPrice>> {private final StockPriceGateway gateway; private final Set<Ticker> stocks;StockPricesBatchCommand(StockPriceGateway gateway, Set<Ticker> stocks) { super(HystrixCommandGroupKey.Factory.asKey("Stock")); this.gateway = gateway; this.stocks = stocks; }@Override protected ImmutableMap<Ticker, StockPrice> run() throws Exception { return gateway.loadAll(stocks); } }The only difference between this class and StockPriceCommand is that it takes a bunch of Tickers and returns prices for all of them. Hystrix will collect a few instances of StockTickerPriceCollapsedCommand and once it has enough(more on that later) it will create single StockPriceCommand. Hope this is clear, because mapResponseToRequests()is slightly more involved. Once our collapsed StockPricesBatchCommand finishes, we must somehow split batch response and communicate replies back to individual commands, unaware of collapsing. From that perspectivemapResponseToRequests() implementation is fairly straightforward: we receive batch response and a collection of wrapped CollapsedRequest<StockPrice, Ticker>. We must now iterate over all awaiting individual requests and complete them (setResponse()). If we don’t complete some of the requests, they will hang infinitely and eventually time out. How it works This is the right moment to describe how collapsing is implemented. I said before that collapsing happens when two requests occur at the same time. There is no such thing as the same time. In reality when first collapsible request comes in, Hystrix starts a timer. In our examples we set it to 100 milliseconds. During that period our command is suspended, waiting for other commands to join. After this configurable period Hystrix will call createCommand(), gathering all request keys (by calling getRequestArgument()) and run it. When batched command finishes, it will let us dispatch results to all awaiting individual commands. It is also possible to limit the number of collapsed requests if we are afraid of creating humongous batch – on the other hand how many concurrent requests can fit within this short time slot? Use cases and drawbacks Request collapsing should be used in systems with extreme load – high frequency of requests. If you get just one request per collapsing time window (100 milliseconds in examples), collapsing will just add overhead. That’s because every time you call collapsible command, it must wait just in case some other command wants to join and form batch. This makes sense only when at least couple of commands are collapsed. Time wasted for waiting is balanced by savings in network latency and/or better utilization of resources in our collaborator (very often batch requests are much faster compared to individual calls). But keep in mind collapsing is a double edged sword, useful in specific cases. Last thing to remember – in order to use request collapsing you needHystrixRequestContext.initializeContext() and shutdown() in try-finally block: HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { //... } finally { context.shutdown(); }Collapsing vs. caching You might think that collapsing can be replaced with proper caching. This is not true. You use cache when:resource is likely to be accessed multiple times we can safely use previous value, it will remain valid for some period of time or we know precisely how to invalidate it we can afford concurrent requests for the same resource to compute it multiple timesOn the other hand collapsing does not enforce locality of data (1), it always hits the real service and never returns stale data (2). And finally if we ask for the same resource from multiple threads, we will only call backing service once (3). In case of caching, unless your cache is really smart, two threads will independently discover absence of given resource in cache and ask backing service twice. However collapsing can work together with caching – by consulting cache before running collapsible command. Summary Request collapsing is a useful tool, but with very limited use cases. It can significantly improve throughput in our system as well as limit load in external service. Collapsing can magically flatten peaks in traffic, rather than spreading it all over. Just make sure you are using it for commands running with extreme frequency.Reference: Batching (collapsing) requests in Hystrix from our JCG partner Tomasz Nurkiewicz at the Java and neighbourhood blog....
codehaus-stomp-logo

STOMP over WebSocket

STOMP is Simple Text Oriented Messaging Protocol. It defines an interoperable wire format that allows a STOMP client to communicate with any STOMP message broker. This provides easy and widespread messaging interoperability among different languages, platforms and brokers. The specification defines what makes it different from other messaging protocols: It is an alternative to other open messaging protocols such as AMQP and implementation specific wire protocols used in JMS brokers such as OpenWire. It distinguishes itself by covering a small subset of commonly used messaging operations rather than providing a comprehensive messaging API. STOMP is a frame-based protocol. A frame consists of a command, a set of optional headers and an optional body. Commonly used commands are:CONNECT SEND SUBSCRIBE UNSCUBSCRIBE ACK NACK DISCONNECTWebSocket messages are also transmitted as frames. STOMP over WebSocket maps STOMP frames to WebSocket frames. Different messaging servers like HornetQ, ActiveMQ, RabbitMQ, and others provide native support for STOMP over WebSocket. Lets take a look at a simple sample on how to use STOMP over WebSocket using ActiveMQ. The source code for the sample is available at github.com/arun-gupta/wildfly-samples/tree/master/websocket-stomp. Lets get started!Download ActiveMQ 5.10 or provision an ActiveMQ instance in OpenShift as explained at github.com/arun-gupta/activemq-openshift-cartridge. workspaces> rhc app-create activemq diy --from-code=git://github.com/arun-gupta/activemq-openshift-cartridge.git Using diy-0.1 (Do-It-Yourself 0.1) for 'diy'Application Options ------------------- Domain: milestogo Cartridges: diy-0.1 Source Code: git://github.com/arun-gupta/activemq-openshift-cartridge.git Gear Size: default Scaling: noCreating application 'activemq' ... doneDisclaimer: This is an experimental cartridge that provides a way to try unsupported languages, frameworks, and middleware on OpenShift.Waiting for your DNS name to be available ... doneCloning into 'activemq'... Warning: Permanently added the RSA host key for IP address '54.90.10.115' to the list of known hosts.Your application 'activemq' is now available.URL: http://activemq-milestogo.rhcloud.com/ SSH to: 545b096a500446e6710004ae@activemq-milestogo.rhcloud.com Git remote: ssh://545b096a500446e6710004ae@activemq-milestogo.rhcloud.com/~/git/activemq.git/ Cloned to: /Users/arungupta/workspaces/activemqRun 'rhc show-app activemq' for more details about your app. workspaces> rhc port-forward activemq Checking available ports ... done Forwarding ports ...To connect to a service running on OpenShift, use the Local addressService Local OpenShift ------- --------------- ---- ----------------- java 127.0.0.1:1883 => 127.7.204.1:1883 java 127.0.0.1:5672 => 127.7.204.1:5672 java 127.0.0.1:61613 => 127.7.204.1:61613 java 127.0.0.1:61614 => 127.7.204.1:61614 java 127.0.0.1:61616 => 127.7.204.1:61616 java 127.0.0.1:8161 => 127.7.204.1:8161Press CTRL-C to terminate port forwardingDownload WildFly 8.1 zip, unzip, and start as bin/standalone.sh Clone the repo and deploy the sample on WildFly: git clone https://github.com/arun-gupta/wildfly-samples.git cd wildfly-samples mvn wildfly:deployAccess the application at localhost:8080/websocket-stomp-1.0-SNAPSHOT/ to see the page as:  Specify text payload “foobar and usse ActiveMQ conventions for topics and queues to specify a queue name as “/queue/myQ1″. Click on Connect, Send Message, Subscribe, and Disconnect buttons one after the other. This will display messages on your browser window where WebSocket connection is established, STOMP message is sent to the queue, subscribed to the queue to receive the message, and then finally disconnected.STOMP frames can be seen using Chrome Developer Tools as shown:   As you can see, each STOMP frame is mapped to a WebSocket frame.In short, ActiveMQ on OpenShift is running a STOMP broker on port 61614 and is accessible on localhost:61614 by port-forwarding. Clicking on Connect button uses the Stomp library bundled with the application to establish a WebSocket connection with ws://localhost:61614/. Subsequent buttons send STOMP frames over WebSocket as shown in the Frames tab of Developer Tools. Read more details about how all the pieces work together at jmesnil.net/stomp-websocket/doc/. Jeff has also written an excellent book explaining STOMP over WebSocket and lot more other interesting things that can be done over WebSocket in his Mobile and Web Messaging book.Reference: STOMP over WebSocket from our JCG partner Arun Gupta at the Miles to go 2.0 … blog....
apache-camel-logo

Apache Camel please explain me what these endpoint options mean

In the upcoming Apache Camel 2.15, we have made Camel smarter. It is now able to act as a teacher and explain to you how its configured and what those options mean. The first lesson Camel can do is to tell you how all the endpoints have been configured and what these option mean. Lessons we are working on next is to let Camel explain the options for the EIPs are. Okay a picture is worth a thousand words, so let me show a screenshot from Apache Karaf, where you can use the new endpoint-explain command to explain how the endpoints have been configured.  The screenshot from Apache is from the SQL example which I have installed in Karaf. This example uses a number of endpoints, and among those a timer to trigger every 5 seconds. As you can see from above, the command list the endpoint uri: timer://foo?period=5s and then explain the option(s) below. As the uri only has 1 option, there is only one listed. We can see that the option is named period. Its java type is a long. The json schema type is integer. We can see the value is 5s, and below the description which explains what the value does. So why is there two types listed? The idea is that there is a type that is suitable for tooling etc, as it has a simpler category of types accordingly to the JSonSchema specification. The actual type in Java is listed as well. The timer endpoint has many more options, so we can use the –verbose option to list all the options, as shown below:The explain endpoint functionality is also available as JMX or as Java API on the CamelContext. For JMX each endpoint mbean has an explain operation that returns a tabular data with the data as above. This is illustrated in the screenshot below from jconsole:In addition there is a generic explainEndpointJson operation on the CamelContext MBean, this allows to explain any arbitrary uri that is provided. So you can explain endpoints that are not in use by Camel. So how does this works? During the built of the Apache Camel release, for each component we generate a HTML and JSon schema where each endpoint option is documented with their name, type, and description. And for enums we list the possible values. Here is an example of such a json schema for the camel-sql component:Now for this to work, the component must support the uri options, which requires to annotation the endpoint with the @UriEndpoint. Though the Camel team has not migrated all the 160+ components in the Camel release yet. But we plan to migrate the components over time. And certainly now where we have this new functionality, it encourages us to migrate all the components. So where do we get the documentation? Well its just java code, so all you have to do is to have getter/setter for an endpoint option. Add the @UriParam annotation, and for the setter you just add javadoc. Yes we grab the javadoc as the documentation. So its just documented in one place and its in the source code, as standard javadoc. I hope we in the future can auto generate the Camel website documentation for the components, so we do not have to maintain that separately in its wiki system. But that would take hard work to implement. But eventually we should get there, so every component is documented in the source code. For example we could have a readme.md for each component that has all the component documentation, and then the endpoint options is injected from the Camel built system into that readme.md file automatic. Having readme.md files also allow github users to browse the Camel component documentation nicely using github style!So what is next? The hawtio web console will integrate this as well, so users with Camel 2.15 onwards have that information in the web console out of the box. And then its onwards to include documentation about the EIP in the XML schemas for Spring/Blueprint users. And improve the javadoc for the EIPs, as that then becomes the single source of documentation as well. This then allows tooling such as Eclipse / IDEA / Netbeans and whatnot to show the documentation when people develop their Camel routes in the XML editor, as the documentation is provided in the XSD as xsd:documentation tags. We have captured some thoughts what else to do in the CAMEL-7999 ticket. If you have any ideas what else to improve or whatnot, then we love feedback from the community.Reference: Apache Camel please explain me what these endpoint options mean from our JCG partner Claus Ibsen at the Claus Ibsen riding the Apache Camel blog....
software-development-2-logo

OptaPlanner – Open benchmarks for the win

Recently, there was some commotion on Twitter because a competitor heavily restricts publicising benchmarks of their Solver as part of their license. That might seem harsh, but I can understand the sentiment: when a competitor publicizes a benchmark report comparing our product against their own, I know we’re gonna get screwed. Unlike single product benchmarking, competitive benchmarking is inherently dishonest…​           Competitive benchmarking for dummies As as competitor, you can utilize several (obvious and not so obvious) means to prove your superiority over another Solver:Publication biasPick a use case which is know to work well in your Solver. Use datasets with a scale and granularity which are known to work well in your Solver. If you’re really evil, benchmark multiple use cases and datasets in both Solvers and only retain those for which your Solver wins.Expertise imbalanceLet one of your experts develop an implementations for both Solvers.Motivation: like any other company, your company only employs experts in your own technology.If he has years of recent experience in your technology, it’s unlikely he’ll had time for any recent experience in the competitive technology.So you’re effectively using your jockey on someone else’s horse.Tweaking imbalanceSpend an equal amount of time on both implementations.The use case is probably already implemented in your Solver (or straightforward to implement), so you can spend most of the time budget to tweak it better. You ‘ll need to learn the competitor’s Solver first, so you ‘ll spend most of the time budget in that implementation to learn the technology, which leaves no room for tweaking.FundingThere’s no need to explicitly set a desired outcome: your developer will know better than to bite the hand that feeds him.Notice how these approaches don’t require any malice (except for the evil one): it’s normal to conduct a competitive benchmark like this…​ Furthermore, you can make the competitive benchmark comparison look more objective, by sponsoring an academic research group to do the benchmark for you. Just make sure that’s a research group which has been happily using your technology for years and has little or no experience with the competition. Marketing value The marketing value of a such a benchmark report should not be underestimated. These numbers, written in black and white, which clearly show the superiority of your Solver against another Solver, make a strong argument:To close sales deals, when in direct competition with the other Solver. To convince developers, researchers and students to learn and use your technology. To build a strong, long-term reputation.Benchmarks from the 90’s can still affect the Google search results today, for example for “performance of Java vs C++”. Such information spreads virally, and counter claims might not.Empirical evidence Are all competitive benchmark reports lying? Yes, they are probably misrepresenting the truth. Should we therefor restrict users from publicizing benchmarks on our Solver? No, of course not (even if our open source licence would allow such conditions, which it does not). Computer science – like any other science – is build on empirical evidence: the promise that any experiment I publish can be repeated by others independently. If we prevent people from publishing such repeated experiments, we undermine our science. In fact, the more people which report their benchmarks, the clearer our strengths and weaknesses show. Historically, this approach has already enabled us to diagnose and fix weaknesses, regardless whether those were caused by our Solver or the user’s domain specific implementation. Therefore, OptaPlanner welcomes external benchmark reports. I believe in Open Science, as strongly as I believe in Open Source. I do ask the courtesy of allowing public comments/feedback on a public report website, as well as to publicize the details (such as the Solver configuration). If you use the OptaPlanner Benchmarker toolkit (which you will find convenient), simply share the benchmarker HTML report. To run any of the benchmarks of the OptaPlanner Examples locally, simply run a *BenchmarkApp executable class, for example CloudBalancingBenchmarkApp. Notice how a small change in the *BenchmarkConfig.xml, such as switching score calculation from Easy Java to Drools or from Drools to Incremental Java, can have a serious effect in the results. In short: I like external benchmarks, but dislike competitive benchmarks, except for …​ Independent research challenges Can we compare fairly with our competition? Yes, through an independent research challenge. Regularly, the academic community launches such challenges. Each challenge:defines a real-world use case with real-world constraints provides multiple, real-world datasets (half of which they keep hidden) expects reproducible results within a specific time limit on specific hardware gets worldwide participation from the academic and/or enterprise Operations Research community benchmarks each contestant’s implementation on the same hardware in the same time limit to determine a winner benchmarks those hidden datasets to counter overfitting and dataset recognitionIt’s fair: each jockey rides his own horse. Most of the arguments against competitive benchmarking do not apply. And as an added bonus, we get to learn from and compare with the academic research community. In the past, OptaPlanner has done well on these challenges, despite the limited weekend time we have to spend on them. In the last challenge, the ICON power scheduling challenge, we (Lukas, Matej and me) finished 2th place. A minority of the researchers still beat us (with their innovative algorithms in their experimental contraptions and massive time to tweak/build those), but it’s been years since a competitive Solver has beaten us. Long term vision Sharing our benchmarks and enabling others to easily reproduce them, is part of a bigger vision: Too many research papers (on metaheuristics and other optimization algorithms) are hard to reproduce. That’s the paradox in computer science research: to reproduce the findings of a research paper, all we really need is a computer and the code. We don’t need an expensive laboratory. Yet, in practice, the code is usually closed and the raw benchmark data is not accessible. It’s like everyone is scared of sharing the dirty secrets of their code and their benchmarks. I believe that we – the worldwide optimization research community – need to create a benchmark repository: a centralized repository of benchmarks for every use case, for every dataset, for every algorithm, for every implementation version, for any amount of running time. That, together with a good statistical interface, will give us some real insight as to which optimization algorithms are good under which circumstances. We – in OptaPlanner – are well on our way to build exactly that:OptaPlanner Examples already implements 14 distinct use cases. For each use case, we’re already benchmarking on many different optimization algorithms. Our benchmarker HTML report already includes many useful statistics to analyse the raw benchmark data.Reference: OptaPlanner – Open benchmarks for the win from our JCG partner Geoffrey De Smet at the OptaPlanner blog....
junit-logo

JUnit Tutorial for Unit Testing – The ULTIMATE Guide (PDF Download)

EDITORIAL NOTE: We have provided plenty of JUnit tutorials here at Java Code Geeks, like JUnit Getting Started Example, JUnit Using Assertions and Annotations Example, JUnit Annotations Example and so on. However, we prefered to gather all the JUnit features in one detailed guide for the convenience of the reader. We hope you like it!        Want to be a JUnit Master ?Subscribe to our newsletter and download the JUnit Ultimate Guide right now! In order to help you master unit testing with JUnit, we have compiled a kick-ass guide with all the major JUnit features and use cases! Besides studying them online you may download the eBook in PDF format!Email address:Given email address is already subscribed, thank you!Oops. Something went wrong. Please try again later.Please provide a valid email address.Thank you, your sign-up request was successful! Please check your e-mail inbox.Please complete the CAPTCHA.Please fill in the required fields.Table Of Contents1. Unit testing introduction1.1. What is unit testing? 1.2. Test coverage 1.3.Unit testing in Java2. JUnit introduction2.1. JUnit Simple Example using Eclipse 2.2. JUnit annotations 2.3. JUnit assertions3. JUnit complete example using Eclipse3.1. Initial steps 3.2. Create a java class to be tested 3.3. Create and run a JUnit test case 3.4. Using @Ignore annotation 3.5. Creating suite tests 3.6. Creating parameterized tests 3.7. Rules 3.8. Categories4. Run JUnit tests from command line 5. Conclusions  1. Unit testing introduction 1.1. What is unit testing? A unit can be a function, a class, a package, or a subsystem. So, the term unit testing refers to the practice of testing such small units of your code, so as to ensure that they work as expected. For example, we can test whether an output is what we expected to see given some inputs or if a condition is true or false. This practice helps developers to discover failures in their logic behind their code and improve the quality of their code. Also, unit testing can be used so as to ensure that the code will work as expected in case of future changes. 1.2. Test coverage In general, the development community has different opinion regarding the percentage of code that should be tested (test coverage). Some developers believe that the code should have 100% test coverage, while others are comprised with a test coverage of 50% or less. In any case, you should write tests for complex or critical parts of your code. 1.3. Unit testing in Java The most popular testing framework in Java is JUnit. As this guide is focused to JUnit, more details for this testing framework will presented in the next sections. Another popular testing framework in Java is TestNG. 2. JUnit introduction JUnit is an open source testing framework which is used to write and run repeatable automated tests, so that we can be ensured that our code works as expected. JUnit is widely used in industry and can be used as stand alone Java program (from the command line) or within an IDE such as Eclipse. JUnit provides:Assertions for testing expected results. Test features for sharing common test data. Test suites for easily organizing and running tests. Graphical and textual test runners.JUnit is used to test:an entire object part of an object – a method or some interacting methods interaction between several objects2.1. JUnit Simple Example using Eclipse In this section we will see a simple JUnit example. First we will present the class we would like to test: Calculate.java package com.javacodegeeks.junit;public class Calculate {public int sum(int var1, int var2) { System.out.println("Adding values: " + var1 + " + " + var2); return var1 + var2; }}In the above source code, we can notice that the class has one public method named sum(), which gets as inputs two integers, adds them and returns the result. So, we will test this method. For this purpose, we will create another class including methods that will test each one of the methods of the previous class (in this case, we have only one method to be tested). This is the most common way of usage. Of course, if a method is very complex and extended, we can have more than one test methods for this complex method. The details of creating test cases will be presented in the next sections. Below, there is the code of the class named CalculateTest.java, which has the role of our test class: CalculateTest.java package com.javacodegeeks.junit;import static org.junit.Assert.*;import org.junit.Test;public class CalculateTest {Calculate calculation = new Calculate(); int sum = calculation.sum(2, 5); int testSum = 7;@Test public void testSum() { System.out.println("@Test sum(): " + sum + " = " + testSum); assertEquals(sum, testSum); }}Let’s explain the above code. Firstly, we can see that there is a @Test annotation above the testSum() method. This annotation indicates that the public void method to which it is attached can be run as a test case. Hence, the testSum() method is the method that will test the sum() public method. We can also observe a method called assertEquals(sum, testsum). The method assertEquals ([String message], object expected, object actual) takes as inputs two objects and asserts that the two objects are equal. If we run the test class, by right-clicking in the test class and select Run As -> Junit Test, the program output will look like that: Adding values: 2 + 5 @Test sum(): 7 = 7To see the actual result of a JUnit test, Eclipse IDE provides a JUnit window which shows the results of the tests. In this case where the test succeeds, the JUnit window does not show any errors or failures, as we can see in the image below:Now, if we change this line of code:int testSum = 10;so that the integers to be tested are not equal, the output will be: Adding values: 2 + 5 @Test sum(): 7 = 10And in the JUnit window, an error will appear and this message will be displayed: java.lang.AssertionError: expected: but was: at com.javacodegeeks.junit.CalculateTest.testSum(CalculateTest.java:16) 2.2. JUnit annotations In this section we will mention the basic annotations supported in Junit 4. The table below presents a summary of those annotations:Annotation Description@Test public void method() The Test annotation indicates that the public void method to which it is attached can be run as a test case.@Before public void method() The Before annotation indicates that this method must be executed before each test in the class, so as to execute some preconditions necessary for the test.@BeforeClass public static void method() The BeforeClass annotation indicates that the static method to which is attached must be executed once and before all tests in the class. That happens when the test methods share computationally expensive setup (e.g. connect to database).@After public void method() The After annotation indicates that this method gets executed after execution of each test (e.g. reset some variables after execution of every test, delete temporary variables etc)@AfterClass public static void method() The AfterClass annotation can be used when a method needs to be executed after executing all the tests in a JUnit Test Case class so as to clean-up the expensive set-up (e.g disconnect from a database). Attention: The method attached with this annotation (similar to BeforeClass) must be defined as static.@Ignore public static void method() The Ignore annotation can be used when you want temporarily disable the execution of a specific test. Every method that is annotated with @Ignore won’t be executed.  Let’s see an example of a test class with some of the annotations mentioned above. AnnotationsTest.java package com.javacodegeeks.junit;import static org.junit.Assert.*; import java.util.*; import org.junit.*;public class AnnotationsTest {private ArrayList testList;@BeforeClass public static void onceExecutedBeforeAll() { System.out.println("@BeforeClass: onceExecutedBeforeAll"); }@Before public void executedBeforeEach() { testList = new ArrayList(); System.out.println("@Before: executedBeforeEach"); }@AfterClass public static void onceExecutedAfterAll() { System.out.println("@AfterClass: onceExecutedAfterAll"); }@After public void executedAfterEach() { testList.clear(); System.out.println("@After: executedAfterEach"); }@Test public void EmptyCollection() { assertTrue(testList.isEmpty()); System.out.println("@Test: EmptyArrayList");}@Test public void OneItemCollection() { testList.add("oneItem"); assertEquals(1, testList.size()); System.out.println("@Test: OneItemArrayList"); }@Ignore public void executionIgnored() {System.out.println("@Ignore: This execution is ignored"); } }If we run the above test, the console output would be the following: @BeforeClass: onceExecutedBeforeAll @Before: executedBeforeEach @Test: EmptyArrayList @After: executedAfterEach @Before: executedBeforeEach @Test: OneItemArrayList @After: executedAfterEach @AfterClass: onceExecutedAfterAll2.3. JUnit assertions In this section we will present a number of assertion methods. All those methods are provided by the Assert class which extends the class java.lang.Object and they are useful for writing tests so as to detect failures. In the table below there is a more detailed explanation of the most commonly used assertion methods.Assertion Descriptionvoid assertEquals([String message], expected value, actual value) Asserts that two values are equal. Values might be type of int, short, long, byte, char or java.lang.Object. The first argument is an optional String message.void assertTrue([String message], boolean condition) Asserts that a condition is true.void assertFalse([String message],boolean condition) Asserts that a condition is false.void assertNotNull([String message], java.lang.Object object) Asserts that an object is not null.void assertNull([String message], java.lang.Object object) Asserts that an object is null.void assertSame([String message], java.lang.Object expected, java.lang.Object actual) Asserts that the two objects refer to the same object.void assertNotSame([String message], java.lang.Object unexpected, java.lang.Object actual) Asserts that the two objects do not refer to the same object.void assertArrayEquals([String message], expectedArray, resultArray) Asserts that the array expected and the resulted array are equal. The type of Array might be int, long, short, char, byte or java.lang.Object.  Let’s see an example of some of the aforementioned assertions. AssertionsTest.java package com.javacodegeeks.junit;import static org.junit.Assert.*; import org.junit.Test;public class AssertionsTest {@Test public void test() { String obj1 = "junit"; String obj2 = "junit"; String obj3 = "test"; String obj4 = "test"; String obj5 = null; int var1 = 1; int var2 = 2; int[] arithmetic1 = { 1, 2, 3 }; int[] arithmetic2 = { 1, 2, 3 };assertEquals(obj1, obj2);assertSame(obj3, obj4);assertNotSame(obj2, obj4);assertNotNull(obj1);assertNull(obj5);assertTrue(var1 var2);assertArrayEquals(arithmetic1, arithmetic2); }}In the class above we can see how these assert methods work.The assertEquals() method will return normally if the two compared objects are equal, otherwise a failure will be displayed in the JUnit window and the test will abort. The assertSame() and assertNotSame() methods tests if two object references point to exactly the same object. The assertNull() and assertNotNull() methods test whether a variable is null or not null. The assertTrue() and assertFalse() methods tests if a condition or a variable is true or false. The assertArrayEquals() will compare the two arrays and if they are equal, the method will proceed without errors. Otherwise, a failure will be displayed in the JUnit window and the test will abort.3. JUnit complete example using Eclipse In this section we will show a complete example of using JUnit. We will see in detail how to create and run tests and we will show how to use specific annotations and assertions of JUnit. 3.1. Initial Steps Let’s create a java project named JUnitGuide. In the src folder, we right-click and select New -> Package, so as to create a new package named com.javacodegeeks.junit where we will locate the class to be tested. For the test classes, it is considered as good practice to create a new source folder dedicated to tests, so that the classes to be tested and the test classes will be in different source folders. For this purpose, right-click your project, select New -> Source Folder, name the new source folder test and click Finish.TipAlternatively, you can create a new source folder by right-clicking your project and select Properties -> Java Build Path, select the tab Source, select Add Folder -> Create New Folder, write the name test and press Finish. You can easily see that there are two source folders in your project:You can also create a new package in the newly created test folder, which will be called com.javacodegeeks.junit, so that your test classes won’t be located to the default package and we are ready to start! 3.2. Create the java class to be tested Right-click the src folder and create a new java class called FirstDayAtSchool.java. This will be the class whose public methods will be tested. FirstDayAtSchool.java package com.javacodegeeks.junit;import java.util.Arrays;public class FirstDayAtSchool {public String[] prepareMyBag() { String[] schoolbag = { "Books", "Notebooks", "Pens" }; System.out.println("My school bag contains: " + Arrays.toString(schoolbag)); return schoolbag; }public String[] addPencils() { String[] schoolbag = { "Books", "Notebooks", "Pens", "Pencils" }; System.out.println("Now my school bag contains: " + Arrays.toString(schoolbag)); return schoolbag; } }3.3. Create and run a JUnit test case To create a JUnit test case for the existing class FirstDayAtSchool.java, right-click on it in the Package Explorer view and select New → JUnit Test Case. Change the source folder so that the class will be located to test source folder and ensure that the flag New JUnit4 test is selected.Then, click Finish. If your project does not contain the JUnit library in its classpath, the following message will be displayed so as to add the JUnit library to the classpath:Below, there is the code of the class named FirstDayAtSchoolTest.java, which is our test class: FirstDayAtSchool.java package com.javacodegeeks.junit;import static org.junit.Assert.*;import org.junit.Test;public class FirstDayAtSchoolTest {FirstDayAtSchool school = new FirstDayAtSchool(); String[] bag1 = { "Books", "Notebooks", "Pens" }; String[] bag2 = { "Books", "Notebooks", "Pens", "Pencils" };@Test public void testPrepareMyBag() { System.out.println("Inside testPrepareMyBag()"); assertArrayEquals(bag1, school.prepareMyBag()); }@Test public void testAddPencils() { System.out.println("Inside testAddPencils()"); assertArrayEquals(bag2, school.addPencils()); }}Now we can run the test case by right-clicking on the test class and select Run As -> JUnit Test. The program output will look like that: Inside testPrepareMyBag() My school bag contains: [Books, Notebooks, Pens] Inside testAddPencils() Now my school bag contains: [Books, Notebooks, Pens, Pencils]and in the JUnit view will be no failures or erros. If we change one of the arrays, so that it contains more than the expected elements:String[] bag2 = { "Books", "Notebooks", "Pens", "Pencils", "Rulers"};and we run again the test class, the JUnit view will contain a failure:Else, if we change again one of the arrays, so that it contains a different element than the expected:String[] bag1 = { "Books", "Notebooks", "Rulers" };and we run again the test class, the JUnit view will contain once again a failure:3.4. Using @Ignore annotation Let’s see in the above example how can we use the @Ignore annotation. In the test class FirstDayAtSchoolTest we will add the @Ignore annotation to the testAddPencils() method. In that way, we expect that this testing method will be ignored and won’t be executed. package com.javacodegeeks.junit;import static org.junit.Assert.*;import org.junit.Ignore; import org.junit.Test;public class FirstDayAtSchoolTest {FirstDayAtSchool school = new FirstDayAtSchool(); String[] bag1 = { "Books", "Notebooks", "Pens" }; String[] bag2 = { "Books", "Notebooks", "Pens", "Pencils" };@Test public void testPrepareMyBag() { System.out.println("Inside testPrepareMyBag()"); assertArrayEquals(bag1, school.prepareMyBag()); }@Ignore @Test public void testAddPencils() { System.out.println("Inside testAddPencils()"); assertArrayEquals(bag2, school.addPencils()); }}Indeed, this is what happens according to the output: Inside testPrepareMyBag() My school bag contains: [Books, Notebooks, Pens]Now, we will remove the @Ignore annotation from the testAddPencils() method and we will annotate the whole class instead. package com.javacodegeeks.junit;import static org.junit.Assert.*;import org.junit.Ignore; import org.junit.Test;@Ignore public class FirstDayAtSchoolTest {FirstDayAtSchool school = new FirstDayAtSchool(); String[] bag1 = { "Books", "Notebooks", "Pens" }; String[] bag2 = { "Books", "Notebooks", "Pens", "Pencils" };@Test public void testPrepareMyBag() { System.out.println("Inside testPrepareMyBag()"); assertArrayEquals(bag1, school.prepareMyBag()); } @Test public void testAddPencils() { System.out.println("Inside testAddPencils()"); assertArrayEquals(bag2, school.addPencils()); }}The whose test class won’t be executed, so no result will be displayed int the console output and in the junit view:3.5. Creating suite tests In this section, we will see how to create suite tests. A test suite is a collection of some test cases from different classes that can be run all together using @RunWith and @Suite annotations. This is very helpful if you have many test classes and you want to run them all together instead of running each test one at a time. When a class is annotated with @RunWith, JUnit will invoke the class in which is annotated so as to run the tests, instead of using the runner built into JUnit. Based on the classes of the previous sections, we can create two test classes. The one class will test the public method prepareMyBag() and the other test class will test the method addPencils(). Hence, we will eventually have the classes below: PrepareMyBagTest.java package com.javacodegeeks.junit;import org.junit.Test; import static org.junit.Assert.*;public class PrepareMyBagTest {FirstDayAtSchool school = new FirstDayAtSchool();String[] bag = { "Books", "Notebooks", "Pens" };@Test public void testPrepareMyBag() {System.out.println("Inside testPrepareMyBag()"); assertArrayEquals(bag, school.prepareMyBag());}}AddPencilsTest.java package com.javacodegeeks.junit;import org.junit.Test; import static org.junit.Assert.*;public class AddPencilsTest {FirstDayAtSchool school = new FirstDayAtSchool();String[] bag = { "Books", "Notebooks", "Pens", "Pencils" };@Test public void testAddPencils() {System.out.println("Inside testAddPencils()"); assertArrayEquals(bag, school.addPencils());}}Now we will create a test suite so as to run the above classes together. Right-click the test source folder and create a new java class named SuiteTest.java with the following code: SuiteTest.java package com.javacodegeeks.junit;import org.junit.runner.RunWith; import org.junit.runners.Suite;@RunWith(Suite.class) @Suite.SuiteClasses({ PrepareMyBagTest.class, AddPencilsTest.class }) public class SuitTest {}With the @Suite.SuiteClasses annotation you can define which test classes will be included in the execution. So, if you right-click the test suite and select Run As -> JUnit Test, the execution of both test classes will take place with the order that has been defined in the @Suite.SuiteClasses annotation. 3.6. Creating parameterized tests In this section we will see how to create parameterized tests. For this purpose, we will use the class mentioned in section 2.1 which provides a public method for adding integers. So, this will be the class to be tested. But when a test class can be considered as a parameterized test class? Of course, when it fullfills all the following requirements:The class is annotated with @RunWith(Parameterized.class). As explained in the previous section, @RunWith annotation enables JUnit to invoke the class in which is annotated to run the tests, instead of using the runner built into JUnit. Parameterized is a runner inside JUnit that will run the same test case with different set of inputs. The class has a single constructor that stores the test data. The class has a static method that generates and returns test data and is annotated with the @Parameters annotation. The class has a test, which obviously means that it needs a method annotated with the @Test annotation.Now, we will create a new test class named CalculateTest.java, which will follow the guidelines mentioned above. The source code of this class follows. CalculateTest.java package com.javacodegeeks.junit;import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.Collection;import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters;@RunWith(Parameterized.class) public class CalculateTest {private int expected; private int first; private int second;public CalculateTest(int expectedResult, int firstNumber, int secondNumber) { this.expected = expectedResult; this.first = firstNumber; this.second = secondNumber; }@Parameters public static Collection addedNumbers() { return Arrays.asList(new Integer[][] { { 3, 1, 2 }, { 5, 2, 3 }, { 7, 3, 4 }, { 9, 4, 5 }, }); }@Test public void sum() { Calculate add = new Calculate(); System.out.println("Addition with parameters : " + first + " and " + second); assertEquals(expected, add.sum(first, second)); } }As we can observe in the class above, it fullfills all the above requirements. The method addedNumbers annotated with @Parameters returns a Collection of Arrays. Each array includes the inputs/output numbers of each test execution. The number of elements in each array must be the same with the number of parameters in the constructor. So, in this specific case, each array includes three elements, two elements that represent the numbers to be added and one element for the result. If we run the CalculateTest test case, the console output will be the following: Addition with parameters : 1 and 2 Adding values: 1 + 2 Addition with parameters : 2 and 3 Adding values: 2 + 3 Addition with parameters : 3 and 4 Adding values: 3 + 4 Addition with parameters : 4 and 5 Adding values: 4 + 5As we see in the output, the test case is executed four times, which is the number of inputs in the method annotated with @Parameters annotation. 3.7. Rules In this section we present a new feature of JUnit called Rules which allows very flexible addition or redefinition of the behavior of each test method in a test class. For this purpose, @Rule annotation should be used so as to mark public fields of a test class. Those fields should be of type MethodRule, which is an alteration in how a test method is run and reported. Multiple MethodRules can be applied to a test method. MethodRule interface has a lot of implementations, such as ErrorCollector which allows execution of a test to continue after the first problem is found, ExpectedException which allows in-test specification of expected exception types and messages, TestName which makes the current test name available inside test methods, and many others. Except for those already defined rules, developers can create their own custom rules and use them in their test cases as they wish. Below we present the way we can use one of the existing rules named TestName in our own tests. TestName is invoked when a test is about to start. NameRuleTest.java package com.javacodegeeks.junit;import static org.junit.Assert.*;import org.junit.*; import org.junit.rules.TestName;public class NameRuleTest { @Rule public TestName name = new TestName();@Test public void testA() { System.out.println(name.getMethodName()); assertEquals("testA", name.getMethodName());}@Test public void testB() { System.out.println(name.getMethodName()); assertEquals("testB", name.getMethodName()); } }We can see that the @Rule annotation marks the public field name which is of type MethodRule and specifically, TestName type. Then, we can use in our tests this name field and find for example the name of the test method, in this specific case. 3.8. Categories Another new feature of JUnit is called Categories and allows you to group certain kinds of tests together and even include or exclude groups (categories). For example, you can separate slow tests from fast tests. To assign a test case or a method to one of those categories the @Category annotation is provided. Below there is an example of how we can use this nice feature of JUnit, based on the release notes of JUnit 4.8. public interface FastTests { /* category marker */ } public interface SlowTests { /* category marker */ } Firstly, we define two categories, FastTests and SlowTests. A category can be either a class or an interface.public class A { @Test public void a() { fail(); }@Category(SlowTests.class) @Test public void b() { } }In the above code, we mark the test method b() of class A with @Category annotation so as to indicate that this specific method belongs to category SlowTests. So, we are able to mark not only whole classes but also some of their test methods individually.@Category({ SlowTests.class, FastTests.class }) public class B { @Test public void c() { } }In the above sample of code, we can see that the whole class B is annotated with @Category annotation . Annotating a test class with @Category annotation automatically includes all its test methods in this category. We can also see that a test class or a test method can belong to more than one categories.@RunWith(Categories.class) @IncludeCategory(SlowTests.class) @SuiteClasses({ A.class, B.class }) // Note that Categories is a kind of Suite public class SlowTestSuite { // Will run A.b and B.c, but not A.a } In this sample of code, we notice that there is a suite test named SlowTestSuite. Basically, categories are a kind of suite. In this suite, we observe a new annotation called @IncludeCategory, indicating which categories will be included in the execution. In this specific case, methods belonging to SlowTests category will be executed. Hence, only the test method b() of class A will be executed as well as the test method c() of class B, which both belong to SlowTests category.@RunWith(Categories.class) @IncludeCategory(SlowTests.class) @ExcludeCategory(FastTests.class) @SuiteClasses({ A.class, B.class }) // Note that Categories is a kind of Suite public class SlowTestSuite { // Will run A.b, but not A.a or B.c }Finally, we change a little bit the test suite and we add one more new annotation called @ExcludeCategory, indicating which categories will be excluded from the execution. In this specific case, only the test method b() of class A will be executed, as this is the only test method that belongs explicitly to SlowTests category. We notice that in both cases, the test method a() of class A won’t be executed as it doesn’t belong to any category. 4. Run JUnit tests from command line You can run your JUnit test outside Eclipse, by using the org.junit.runner.JUnitCore class. This class provides the runClasses() method which allows you to execute one or several test classes. The return type of runClasses() method is an object of the type org.junit.runner.Result. This object can be used to collect information about the tests. Also, in case there is a failed test, you can use the object org.junit.runner.notification.Failure which holds description of the failed tests. The procedure below shows how to run your test outside Eclipse. Create a new Java class named JunitRunner.java with the following code: JunitRunner.java package com.javacodegeeks.junit;import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure;public class JunitRunner {public static void main(String[] args) {Result result = JUnitCore.runClasses(AssertionsTest.class); for (Failure fail : result.getFailures()) { System.out.println(fail.toString()); } if (result.wasSuccessful()) { System.out.println("All tests finished successfully..."); } } }As an example, we choose to run the AssertionsTest test class.Open command prompt and move down directories so as to find the directory where the two classes are located. Compile the Test class and the Runner class. C:\Users\konstantina\eclipse_luna_workspace\JUnitGuide\test\com\javacodegeeks\junit>javac -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; AssertionsTest.java JunitRunner.java As we did in Eclipse, we should also include library jars of JUnit to our classpath. Now run the JunitRunner. C:\Users\konstantina\eclipse_luna_workspace\JUnitGuide\test\com\javacodegeeks\junit>java -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; JunitRunnerHere is the output: All tests finished successfully...5. Conclusions This was a detailed guide about JUnit testing framework, the most popular testing framework in Java. If you enjoyed this, then subscribe to our newsletter to enjoy weekly updates and complimentary whitepapers! Also, check out JCG Academy for more advanced training! DownloadYou can download the full source code of this guide here : JUnitGuide.zip ...
java-logo

10 Things You Didn’t Know About Java

So, you’ve been working with Java since the very beginning? Remember the days when it was called “Oak”, when OO was still a hot topic, when C++ folks thought that Java had no chance, when Applets were still a thing? I bet that you didn’t know at least half of the following things. Let’s start this week with some great surprises about the inner workings of Java.           1. There is no such thing as a checked exception That’s right! The JVM doesn’t know any such thing, only the Java language does. Today, everyone agrees that checked exceptions were a mistake. As Bruce Eckel said on his closing keynote at GeeCON, Prague, no other language after Java has engaged in using checked exceptions, and even Java 8 does no longer embrace them in the new Streams API (which can actually be a bit of a pain, when your lambdas use IO or JDBC). Do you want proof that the JVM doesn’t know such a thing? Try the following code: public class Test { // No throws clause here public static void main(String[] args) { doThrow(new SQLException()); } static void doThrow(Exception e) { Test.<RuntimeException> doThrow0(e); } @SuppressWarnings("unchecked") static <E extends Exception> void doThrow0(Exception e) throws E { throw (E) e; } } Not only does this compile, this also actually throws the SQLException, you don’t even need Lombok’s @SneakyThrows for that.More details about the above can be found in this article here, or here, on Stack Overflow.2. You can have method overloads differing only in return types That doesn’t compile, right? class Test { Object x() { return "abc"; } String x() { return "123"; } } Right. The Java language doesn’t allow for two methods to be “override-equivalent” within the same class, regardless of their potentially differing throws clauses or return types. But wait a second. Check out the Javadoc of Class.getMethod(String, Class...). It reads:Note that there may be more than one matching method in a class because while the Java language forbids a class to declare multiple methods with the same signature but different return types, the Java virtual machine does not. This increased flexibility in the virtual machine can be used to implement various language features. For example, covariant returns can be implemented with bridge methods; the bridge method and the method being overridden would have the same signature but different return types.Wow, yes that makes sense. In fact, that’s pretty much what happens when you write the following: abstract class Parent<T> { abstract T x(); }class Child extends Parent<String> { @Override String x() { return "abc"; } } Check out the generated byte code in Child: // Method descriptor #15 ()Ljava/lang/String; // Stack: 1, Locals: 1 java.lang.String x(); 0 ldc <String "abc"> [16] 2 areturn Line numbers: [pc: 0, line: 7] Local variable table: [pc: 0, pc: 3] local: this index: 0 type: Child // Method descriptor #18 ()Ljava/lang/Object; // Stack: 1, Locals: 1 bridge synthetic java.lang.Object x(); 0 aload_0 [this] 1 invokevirtual Child.x() : java.lang.String [19] 4 areturn Line numbers: [pc: 0, line: 1] So, T is really just Object in byte code. That’s well understood. The synthetic bridge method is actually generated by the compiler because the return type of the Parent.x() signature may be expected to Object at certain call sites. Adding generics without such bridge methods would not have been possible in a binary compatible way. So, changing the JVM to allow for this feature was the lesser pain (which also allows covariant overriding as a side-effect…) Clever, huh? Are you into language specifics and internals? Then find some more very interesting details here. 3. All of these are two-dimensional arrays! class Test { int[][] a() { return new int[0][]; } int[] b() [] { return new int[0][]; } int c() [][] { return new int[0][]; } } Yes, it’s true. Even if your mental parser might not immediately understand the return type of the above methods, they are all the same! Similar to the following piece of code: class Test { int[][] a = {{}}; int[] b[] = {{}}; int c[][] = {{}}; } You think that’s crazy? Imagine using JSR-308 / Java 8 type annotations on the above. The number of syntactic possibilities explodes! @Target(ElementType.TYPE_USE) @interface Crazy {}class Test { @Crazy int[][] a1 = {{}}; int @Crazy [][] a2 = {{}}; int[] @Crazy [] a3 = {{}};@Crazy int[] b1[] = {{}}; int @Crazy [] b2[] = {{}}; int[] b3 @Crazy [] = {{}};@Crazy int c1[][] = {{}}; int c2 @Crazy [][] = {{}}; int c3[] @Crazy [] = {{}}; }Type annotations. A device whose mystery is only exceeded by its powerOr in other words:When I do that one last commit just before my 4 week vacationI let the actual exercise of finding a use-case for any of the above to you. 4. You don’t get the conditional expression So, you thought you knew it all when it comes to using the conditional expression? Let me tell you, you didn’t. Most of you will think that the below two snippets are equivalent: Object o1 = true ? new Integer(1) : new Double(2.0); … the same as this? Object o2;if (true) o2 = new Integer(1); else o2 = new Double(2.0); Nope. Let’s run a quick test System.out.println(o1); System.out.println(o2); This programme will print: 1.0 1 Yep! The conditional operator will implement numeric type promotion, if “needed”, with a very very very strong set of quotation marks on that “needed”. Because, would you expect this programme to throw a NullPointerException? Integer i = new Integer(1); if (i.equals(1)) i = null; Double d = new Double(2.0); Object o = true ? i : d; // NullPointerException! System.out.println(o);More information about the above can be found here.5. You also don’t get the compound assignment operator Quirky enough? Let’s consider the following two pieces of code: i += j; i = i + j; Intuitively, they should be equivalent, right? But guess what. They aren’t! The JLS specifies:A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.This is so beautiful, I would like to cite Peter Lawrey‘s answer to this Stack Overflow question:A good example of this casting is using *= or /= byte b = 10; b *= 5.7; System.out.println(b); // prints 57 or byte b = 100; b /= 2.5; System.out.println(b); // prints 40 or char ch = '0'; ch *= 1.1; System.out.println(ch); // prints '4' or char ch = 'A'; ch *= 1.5; System.out.println(ch); // prints 'a'Now, how incredibly useful is that? I’m going to cast/multiply chars right there in my application. Because, you know… 6. Random integers Now, this is more of a puzzler. Don’t read the solution yet. See if you can find this one out yourself. When I run the following programme: for (int i = 0; i < 10; i++) { System.out.println((Integer) i); } … then “sometimes”, I get the following output: 92 221 45 48 236 183 39 193 33 84 How is that even possible?? . . . . . . spoiler… solution ahead… . . . . . OK, the solution is here and has to do with overriding the JDK’s Integer cache via reflection, and then using auto-boxing and auto-unboxing. Don’t do this at home! Or in other words, let’s think about it this way, once moreWhen I do that one last commit just before my 4 week vacation7. GOTO This is one of my favourite. Java has GOTO! Type it… int goto = 1; This will result in: Test.java:44: error: <identifier> expected int goto = 1; ^ This is because goto is an unused keyword, just in case… But that’s not the exciting part. The exciting part is that you can actually implement goto with break, continue and labelled blocks: Jumping forward label: { // do stuff if (check) break label; // do more stuff } In bytecode: 2 iload_1 [check] 3 ifeq 6 // Jumping forward 6 .. Jumping backward label: do { // do stuff if (check) continue label; // do more stuff break label; } while(true); In bytecode: 2 iload_1 [check] 3 ifeq 9 6 goto 2 // Jumping backward 9 .. 8. Java has type aliases In other languages (e.g. Ceylon), we can define type aliases very easily: interface People => Set<Person>; A People type constructed in such a way can then be used interchangably with Set<Person>: People? p1 = null; Set<Person>? p2 = p1; People? p3 = p2; In Java, we can’t define type aliases at a top level. But we can do so for the scope of a class, or a method. Let’s consider that we’re unhappy with the namings of Integer, Long etc, we want shorter names: I and L. Easy: class Test<I extends Integer> { <L extends Long> void x(I i, L l) { System.out.println( i.intValue() + ", " + l.longValue() ); } } In the above programme, Integer is “aliased” to I for the scope of the Test class, whereas Long is “aliased” to L for the scope of the x() method. We can then call the above method like this: new Test().x(1, 2L); This technique is of course not to be taken seriously. In this case, Integer and Long are both final types, which means that the types I and L are effectively aliases (almost. assignment-compatibility only goes one way). If we had used non-final types (e.g. Object), then we’d be really using ordinary generics. Enough of these silly tricks. Now for something truly remarkable! 9. Some type relationships are undecidable! OK, this will now get really funky, so take a cup of coffee and concentrate. Consider the following two types: // A helper type. You could also just use List interface Type<T> {}class C implements Type<Type<? super C>> {} class D<P> implements Type<Type<? super D<D<P>>>> {} Now, what do the types C and D even mean? They are somewhat recursive, in a similar (yet subtly different) way that java.lang.Enum is recursive. Consider: public abstract class Enum<E extends Enum<E>> { ... } With the above specification, an actual enum implementation is just mere syntactic sugar: // This enum MyEnum {}// Is really just sugar for this class MyEnum extends Enum<MyEnum> { ... } With this in mind, let’s get back to our two types. Does the following compile? class Test { Type<? super C> c = new C(); Type<? super D<Byte>> d = new D<Byte>(); } Hard question, and Ross Tate has an answer to it. The question is in fact undecidable: Is C a subtype of Type<? super C>? Step 0) C <?: Type<? super C> Step 1) Type<Type<? super C>> <?: Type (inheritance) Step 2) C (checking wildcard ? super C) Step . . . (cycle forever) And then: Is D a subtype of Type<? super D<Byte>>? Step 0) D<Byte> <?: Type<? super C<Byte>> Step 1) Type<Type<? super D<D<Byte>>>> <?: Type<? super D<Byte>> Step 2) D<Byte> <?: Type<? super D<D<Byte>>> Step 3) List<List<? super C<C>>> <?: List<? super C<C>> Step 4) D<D<Byte>> <?: Type<? super D<D<Byte>>> Step . . . (expand forever) Try compiling the above in your Eclipse, it’ll crash! (don’t worry. I’ve filed a bug) Let this sink in…Some type relationships in Java are undecidable!If you’re interested in more details about this peculiar Java quirk, read Ross Tate’s paper “Taming Wildcards in Java’s Type System” (co-authored with Alan Leung and Sorin Lerner), or also our own musings on correlating subtype polymorphism with generic polymorphism 10. Type intersections Java has a very peculiar feature called type intersections. You can declare a (generic) type that is in fact the intersection of two types. For instance: class Test<T extends Serializable & Cloneable> { } The generic type parameter T that you’re binding to instances of the class Test must implement both Serializable and Cloneable. For instance, String is not a possible bound, but Date is: // Doesn't compile Test<String> s = null;// Compiles Test<Date> d = null; This feature has seen reuse in Java 8, where you can now cast types to ad-hoc type intersections. How is this useful? Almost not at all, but if you want to coerce a lambda expression into such a type, there’s no other way. Let’s assume you have this crazy type constraint on your method: <T extends Runnable & Serializable> void execute(T t) {} You want a Runnable that is also Serializable just in case you’d like to execute it somewhere else and send it over the wire. Lambdas and serialisation are a bit of a quirk. Lambdas can be serialised:You can serialize a lambda expression if its target type and its captured arguments are serializableBut even if that’s true, they do not automatically implement the Serializable marker interface. To coerce them to that type, you must cast. But when you cast only to Serializable… execute((Serializable) (() -> {})); … then the lambda will no longer be Runnable. Egh… So… Cast it to both types: execute((Runnable & Serializable) (() -> {})); Conclusion I usually say this only about SQL, but it’s about time to conclude an article with the following:Java is a device whose mystery is only exceeded by its power.Reference: 10 Things You Didn’t Know About Java from our JCG partner Lukas Eder at the JAVA, SQL, AND JOOQ blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close