DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Popular Topics

article thumbnail
What Does a Java Array Look Like in Memory?
arrays in java store one of two things: either primitive values (int, char, …) or references (a.k.a pointers). when an object is creating by using “new”, memory is allocated on the heap and a reference is returned. this is also true for arrays. 1. single-dimension array int arr[] = new int[3]; the int[] arr is just the reference to the array of 3 integer. if you create an array with 10 integer, it is the same – an array is allocated and a reference is returned. 2. two-dimensional array how about 2-dimensional array? actually, we can only have one dimensional arrays in java. 2d arrays are basically just one dimensional arrays of one dimensional arrays. int[ ][ ] arr = new int[3][ ]; arr[0] = new int[3]; arr[1] = new int[5]; arr[2] = new int[4]; multi-dimensional arrays use the name rules. 3. where are they located in memory? from the above, there are arrays and reference variables in memory. as we know that jvm runtime data areas include heap, jvm stack, and others. for a simple example as follows, let’s see where the array and its reference are stored. class a { int x; int y; } ... public void m1() { int i = 0; m2(); } public void m2() { a a = new a(); } ... when m1 is invoked, a new frame (frame-1) is pushed into the stack, and local variable i is also created in frame-1. when m2 is invoked inside of m1, another new frame (frame-2) is pushed into the stack. in m2, an object of class a is created in the heap and reference variable is put in frame-2. now, at this point, the stack and heap looks like the following: arrays are treated the same way like objects, so how array locates in memory is straight-forward.
April 19, 2013
by Ryan Wang
· 31,317 Views · 1 Like
article thumbnail
SiftingAppender: Logging Different Threads to Different Log Files
One novel feature of Logback is SiftingAppender (JavaDoc). In short it's a proxy appender that creates one child appender per each unique value of a given runtime property. Typically this property is taken from MDC. Here is an example based on the official documentation linked above: userid unknown user-${userid}.log %d{HH:mm:ss:SSS} | %-5level | %thread | %logger{20} | %msg%n%rEx Notice that the property is parameterized with ${userid} property. Where does this property come from? It has to be placed in MDC. For example in a web application using Spring Security I tend to use a servlet filter with a help of SecurityContextHolder: import javax.servlet._ import org.slf4j.MDC import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.UserDetails class UserIdFilter extends Filter { def init(filterConfig: FilterConfig) {} def doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) { val userid = Option( SecurityContextHolder.getContext.getAuthentication ).collect{case u: UserDetails => u.getUsername} MDC.put("userid", userid.orNull) try { chain.doFilter(request, response) } finally { MDC.remove("userid") } } def destroy() {} } Just make sure this filter is applied after Spring Security filter. But that's not the point. The presence of ${userid} placeholder in the file name causes sifting appender to create one child appender for each different value of this property (thus: different user names). Running your web application with this configuration will quickly create several log files like user-alice.log, user-bob.log and user-unknown.log in case of MDC property not set. Another use case is using thread name rather than MDC property. Unfortunately this is not built in, but can be easily plugged in using custom Discriminator as opposed to default MDCBasedDiscriminator: public class ThreadNameBasedDiscriminator implements Discriminator { private static final String KEY = "threadName"; private boolean started; @Override public String getDiscriminatingValue(ILoggingEvent iLoggingEvent) { return Thread.currentThread().getName(); } @Override public String getKey() { return KEY; } public void start() { started = true; } public void stop() { started = false; } public boolean isStarted() { return started; } } Now we have to instruct logback.xml to use our custom discriminator: app-${threadName}.log %d{HH:mm:ss:SSS} | %-5level | %logger{20} | %msg%n%rEx Note that we no longer put %thread in PatternLayout - it is unnecessary as thread name is part of the log file name: app-main.log app-http-nio-8080-exec-1.log app-taskScheduler-1 app-ForkJoinPool-1-worker-1.log ...and so forth This is probably not the most convenient setup for server application, but on desktop where you have a limited number of focused threads like EDT, IO thread, etc. it might be a vital alternative.
April 19, 2013
by Tomasz Nurkiewicz
· 38,027 Views · 3 Likes
article thumbnail
HotSpot GC Thread CPU footprint on Linux
The following question will test your knowledge on garbage collection and high CPU troubleshooting for Java applications running on Linux OS. This troubleshooting technique is especially crucial when investigating excessive GC and / or CPU utilization. It will assume that you do not have access to advanced monitoring tools such as Compuware dynaTrace or even JVisualVM. Future tutorials using such tools will be presented in the future but please ensure that you first master the base troubleshooting principles. Question: How can you monitor and calculate how much CPU % each of the Oracle HotSpot or JRockit JVM garbage collection (GC) threads is using at runtime on Linux OS? Answer: On the Linux OS, Java threads are implemented as native Threads, which results in each thread being a separate Linux process. This means that you are able to monitor the CPU % of any Java thread created by the HotSpot JVM using the top –H command (Threads toggle view). That said, depending of the GC policy that you are using and your server specifications, the HotSpot & JRockit JVM will create a certain number of GC threads that will be performing young and old space collections. Such threads can be easily identified by generating a JVM thread dump. As you can see below in our example, the Oracle JRockit JVM did create 4 GC threads identified as "(GC Worker Thread X)”. ===== FULL THREAD DUMP =============== Fri Nov 16 19:58:36 2012 BEA JRockit(R) R27.5.0-110-94909-1.5.0_14-20080204-1558-linux-ia32 "Main Thread" id=1 idx=0x4 tid=14911 prio=5 alive, in native, waiting -- Waiting for notification on: weblogic/t3/srvr/T3Srvr@0xfd0a4b0[fat lock] at jrockit/vm/Threads.waitForNotifySignal(JLjava/lang/Object;)Z(Native Method) at java/lang/Object.wait(J)V(Native Method) at java/lang/Object.wait(Object.java:474) at weblogic/t3/srvr/T3Srvr.waitForDeath(T3Srvr.java:730) ^-- Lock released while waiting: weblogic/t3/srvr/T3Srvr@0xfd0a4b0[fat lock] at weblogic/t3/srvr/T3Srvr.run(T3Srvr.java:380) at weblogic/Server.main(Server.java:67) at jrockit/vm/RNI.c2java(IIIII)V(Native Method) -- end of trace "(Signal Handler)" id=2 idx=0x8 tid=14920 prio=5 alive, in native, daemon "(GC Main Thread)" id=3 idx=0xc tid=14921 prio=5 alive, in native, native_waiting, daemon "(GC Worker Thread 1)" id=? idx=0x10 tid=14922 prio=5 alive, in native, daemon "(GC Worker Thread 2)" id=? idx=0x14 tid=14923 prio=5 alive, in native, daemon "(GC Worker Thread 3)" id=? idx=0x18 tid=14924 prio=5 alive, in native, daemon "(GC Worker Thread 4)" id=? idx=0x1c tid=14925 prio=5 alive, in native, daemon ……………………… Now let’s put all of these principles together via a simple example. Step #1 - Monitor the GC thread CPU utilization The first step of the investigation is to monitor and determine: Identify the native Thread ID for each GC worker thread shown via the Linux top –H command. Identify the CPU % for each GC worker thread. Step #2 – Generate and analyze JVM Thread Dumps At the same time of Linux top –H, generate 2 or 3 JVM Thread Dump snapshots via kill -3 . Open the JVM Thread Dump and locate the JVM GC worker threads. Now correlate the "top -H" output data with the JVM Thread Dump data by looking at the native thread id (tid attribute). As you can see in our example, such analysis did allow us to determine that all our GC worker threads were using around 20% CPU each. This was due to major collections happening at that time. Please note that it is also very useful to enable verbose:gc as it will allow you to correlate such CPU spikes with minor and major collections and determine how much your JVM GC process is contributing to the overall server CPU utilization.
April 17, 2013
by Pierre - Hugues Charbonneau
· 14,518 Views
article thumbnail
Java Optional Objects
In this post I present several examples of the new Optional objects in Java 8 and I make comparisons with similar approaches in other programming languages, particularly the functional programming language SML and the JVM-based programming language Ceylon, this latter currently under development by Red Hat. I think it is important to highlight that the introduction of optional objects has been a matter of debate. In this article I try to present my perspective of the problem and I do an effort to show arguments in favor and against the use of optional objects. It is my contention that in certain scenarios the use of optional objects is valuable, but ultimately everyone is entitled to an opinion and I just hope this article helps the readers to make an informed one just as writing it helped me understand this problem much better. About the Type of Null In Java we use a reference type to gain access to an object, and when we don't have a specific object to make our reference point to, then we set such reference to null to imply the absence of a value. In Java null is actually a type, a special one: it has no name, we cannot declare variables of its type, or cast any variables to it, in fact there is a single value that can be associated with it (i.e. the literal null), and unlike any other types in Java, a null reference can be safely assigned to any other reference types (See JLS 3.10.7 and 4.1). The use of null is so common that we rarely meditate on it: field members of objects are automatically initialized to null and programmers typically initialize reference types to null when they don't have an initial value to give them and, in general, null is used everywhere to imply that, at certain point, we don't know or we don't have a value to give to a reference. About the Null Pointer Reference Problem Now, the major problem with the null reference is that if we try to dereference it then we get the ominous and well known NullPointerException. When we work with a reference obtained from a different context than our code (i.e. as the result of a method invocation or when we receive a reference as an argument in a method we are working on), we all would like to avoid this error that has the potential to make our application crash, but often the problem is not noticed early enough and it finds its way into production code where it waits for the right moment to fail (which is typically a Friday at the end of the month, around 5 p.m. and just when you are about to leave the office to go to the movies with your family or drink some beers with your friends). To make things worse, the place where your code fails is rarely the place where the problem originated, since your reference could have been set to null far away from the place in your code where you intended to dereference it. So, you better cancel those plans for the Friday night... It's worth mentioning that this concept of null references was first introduced by Tony Hoare, the creator of ALGOL, back in 1965. The consequences were not so evident in those days, but he later regretted his design and he called it "a billion dollars mistake", precisely referring to the uncountable amount of hours that many of us have spent, since then, fixing this kind null dereferencing problems. Wouldn't it be great if the type system could tell the difference between a reference that, in a specific context, could be potentially null from one that couldn't? This would help a lot in terms of type safety because the compiler could then enforce that the programmer do some verification for references that could be null at the same time that it allows a direct use of the others. We see here an opportunity for improvement in the type system. This could be particularly useful when writing the public interface of APIs because it would increase the expressive power of the language, giving us a tool, besides documentation, to tell our users that a given method may or may not return a value. Now, before we delve any further, I must clarify that this is an ideal that modern languages will probably pursue (we'll talk about Ceylon and Kotlin later), but it is not an easy task to try to fix this hole in a programming language like Java when we intend to do it as an afterthought. So, in the coming paragraphs I present some scenarios in which I believe the use of optional objects could arguably alleviate some of this burden. Even so, the evil is done, and nothing will get rid of null references any time soon, so we better learn to deal with them. Understanding the problem is one step and it is my opinion that these new optional objects are just another way to deal with it, particularly in certain specific scenarios in which we would like to express the absence of a value. Finding Elements There is a set of idioms in which the use of null references is potentially problematic. One of those common cases is when we look for something that we cannot ultimately find. Consider now the following simple piece of code used to find the first fruit in a list of fruits that has a certain name: public static Fruit find(String name, List fruits) { for(Fruit fruit : fruits) { if(fruit.getName().equals(name)) { return fruit; } } return null; } As we can see, the creator of this code is using a null reference to indicate the absence of a value that satisfies the search criteria (7). It is unfortunate, though, that it is not evident in the method signature that this method may not return a value, but a null reference.. Now consider the following code snippet, written by a programmer expecting to use the result of the method shown above: List fruits = asList(new Fruit("apple"), new Fruit("grape"), new Fruit("orange")); Fruit found = find("lemon", fruits); //some code in between and much later on (or possibly somewhere else)... String name = found.getName(); //uh oh! Such simple piece of code has an error that cannot be detected by the compiler, not even by simple observation by the programmer (who may not have access to the source code of the find method). The programmer, in this case, has naively failed to recognize the scenario in which the find method above could return a null reference to indicate the absence of a value that satisfies his predicate. This code is waiting to be executed to simply fail and no amount of documentation is going to prevent this mistake from happening and the compiler will not even notice that there is a potential problem here. Also notice that the line where the reference is set to null (5) is different from the problematic line (7). In this case they were close enough, in other cases this may not be so evident. In order to avoid the problem what we typically do is that we check if a given reference is null before we try to dereference it. In fact, this verification is quite common and in certain cases this check could be repeated so many times on a given reference that Martin Fowler (renown for hist book on refactoring principles) suggested that for these particular scenarios such verification could be avoided with the use of what he called a Null Object. In our example above, instead of returning null, we could have returned a NullFruit object reference which is an object of type Fruit that is hollowed inside and which, unlike a null reference, is capable of properly responding to the same public interface of a Fruit. Minimum and Maximum Another place where this could be potentially problematic is when reducing a collection to a value, for instance to a maximum or minimum value. Consider the following piece of code that can be used to determine which is the longest string in a collection. public static String longest(Collection items) { if(items.isEmpty()){ return null; } Iterator iter = items.iterator(); String result = iter.next(); while(iter.hasNext()) { String item = iter.next(); if(item.length() > result.length()){ result = item; } } return result; } In this case the question is what should be returned when the list provided is empty? In this particular case a null value is returned, once again, opening the door for a potential null dereferencing problem. The Functional World Strategy It's interesting that in the functional programming paradigm, the statically-typed programming languages evolved in a different direction. In languages like SML or Haskell there is no such thing as a null value that causes exceptions when dereferenced. These languages provide a special data type capable of holding an optional value and so it can be conveniently used to also express the possible absence of a value. The following piece of code shows the definition of the SML option type: datatype 'a option = NONE | SOME of 'a As you can see, option is a data type with two constructors, one of them stores nothing (i.e. NONE) whereas the other is capable of storing a polymorphic value of some value type 'a (where 'a is just a placeholder for the actual type). Under this model, the piece of code we wrote before in Java, to find a fruit by its name, could be rewritten in SML as follows: fun find(name, fruits) = case fruits of [] => NONE | (Fruit s)::fs => if s = name then SOME (Fruit s) else find(name,fs) There are several ways to achieve this in SML, this example just shows one way to do it. The important point here is that there is no such thing as null, instead a value NONE is returned when nothing is found (3), and a value SOME fruit is returned otherwise (5). When a programmer uses this find method, he knows that it returns an option type value and therefore the programmer is forced to check the nature of the value obtained to see if it is either NONE (6) or SOME fruit (7), somewhat like this: let val fruits = [Fruit "apple", Fruit "grape", Fruit "orange"] val found = find("grape", fruits) in case found of NONE => print("Nothing found") | SOME(Fruit f) => print("Found fruit: " ^ f) end Having to check for the true nature of the returned option makes it impossible to misinterpret the result. Java Optional Types It's a joy that finally in Java 8 we'll have a new class called Optional that allows us to implement a similar idiom as that from the functional world. As in the case of of SML, the Optional type is polymorphic and may contain a value or be empty. So, we could rewrite our previous code snippet as follows: public static Optional find(String name, List fruits) { for(Fruit fruit : fruits) { if(fruit.getName().equals(name)) { return Optional.of(fruit); } } return Optional.empty(); } As you can see, the method now returns an Optional reference (1), if something is found, the Optional object is constructed with a value (4), otherwise is constructed empty (7). And the programmer using this code would do something as follows: List fruits = asList(new Fruit("apple"), new Fruit("grape"), new Fruit("orange")); Optional found = find("lemon", fruits); if(found.isPresent()) { Fruit fruit = found.get(); String name = fruit.getName(); } Now it is made evident in the type of the find method that it returns an optional value (5), and the user of this method has to program his code accordingly (6-7). So we see that the adoption of this functional idiom is likely to make our code safer, less prompt to null dereferencing problems and as a result more robust and less error prone. Of course, it is not a perfect solution because, after all, Optional references can also be erroneously set to null references, but I would expect that programmers stick to the convention of not passing null references where an optional object is expected, pretty much as we today consider a good practice not to pass a null reference where a collection or an array is expected, in these cases the correct is to pass an empty array or collection. The point here is that now we have a mechanism in the API that we can use to make explicit that for a given reference we may not have a value to assign it and the user is forced, by the API, to verify that. Quoting an article I reference later about the use of optional objects in the Guava Collections framework: "Besides the increase in readability that comes from giving null a name, the biggest advantage of Optional is its idiot-proof-ness. It forces you to actively think about the absent case if you want your program to compile at all, since you have to actively unwrap the Optional and address that case". Other Convenient Methods As of the today, besides the static methods of and empty explained above, the Optional class contains the following convenient instance methods: ifPresent() Which returns true if a value is present in the optional. get() Which returns a reference to the item contained in the optional object, if present, otherwise throws a NoSuchElementException. ifPresent(Consumer consumer) Which passess the optional value, if present, to the provided Consumer (which could be implemented through a lambda expression or method reference). orElse(T other) Which returns the value, if present, otherwise returns the value in other. orElseGet(Supplier other) Which returns the value if present, otherwise returns the value provided by the Supplier (which could be implemented with a lambda expression or method reference). orElseThrow(Supplier exceptionSupplier) Which returns the value if present, otherwise throws the exception provided by the Supplier (which could be implemented with a lambda expression or method reference). Avoiding Boilerplate Presence Checks We can use some of the convenient methods mentioned above to avoid the need of having to check if a value is present in the optional object. For instance, we may want to use a default fruit value if nothing is found, let's say that we would like to use a "Kiwi". So we could rewrite our previous code like this: Optional found = find("lemon", fruits); String name = found.orElse(new Fruit("Kiwi")).getName(); In this other example, the code prints the fruit name to the main output, if the fruit is present. In this case, we implement the Consumer with a lambda expression. Optional found = find("lemon", fruits); found.ifPresent(f -> { System.out.println(f.getName()); }); This other piece of code uses a lambda expression to provide a Supplier which can ultimately provide a default answer if the optional object is empty: Optional found = find("lemon", fruits); Fruit fruit = found.orElseGet(() -> new Fruit("Lemon")); Clearly, we can see that these convenient methods simplify a lot having to work with the optional objects. So What's Wrong with Optional? The question we face is: will Optional get rid of null references? And the answer is an emphatic no! So, detractors immediately question its value asking: then what is it good for that we couldn't do by other means already? Unlike functional languages like SML o Haskell which never had the concept of null references, in Java we cannot simply get rid of the null references that have historically existed. This will continue to exist, and they arguably have their proper uses (just to mention an example: three-valued logic). I doubt that the intention with the Optional class is to replace every single nullable reference, but to help in the creation of more robust APIs in which just by reading the signature of a method we could tell if we can expect an optional value or not and force the programmer to use this value accordingly. But ultimately, Optional will be just another reference and subject to same weaknesses of every other reference in the language. It is quite evident that Optional is not going to save the day. How these optional objects are supposed to be used or whether they are valuable or not in Java has been the matter of a heated debate in the project lambda mailing list. From the detractors we hear interesting arguments like: The fact that other alternatives exist ( i.e. the Eclipse IDE supports a set of proprietary annotations for static analysis of nullability, the JSR-305 with annotations like @Nullable and @NonNull). Some would like it to be usable as in the functional world, which is not entirely possible in Java since the language lacks many features existing in functional programming languages like SML or Haskell (i.e. pattern matching). Others argue about how it is impossible to retrofit preexisting code to use this idiom (i.e. List.get(Object)which will continue to return null). And some complain about the fact that the lack of language support for optional values creates a potential scenario in which Optional could be used inconsistently in the APIs, by this creating incompatibilities, pretty much like the ones we will have with the rest of the Java API which cannot be retrofitted to use the new Optional class. A compelling argument is that if the programmer invokes the get method in an optional object, if it is empty, it will raise a NoSuchElementException, which is pretty much the same problem that we have with nulls, just with a different exception. So, it would appear that the benefits of Optional are really questionable and are probably constrained to improving readability and enforcing public interface contracts. Optional Objects in the Stream API Irrespective of the debate, the optional objects are here to stay and they are already being used in the new Stream API in methods like findFirst, findAny, max and min. It could be worth mentioning that a very similar class has been in used in the successful Guava Collections Framework. For instance, consider the following example where we extract from a stream the last fruit name in alphabetical order: Stream fruits = asList(new Fruit("apple"), new Fruit("grape")).stream(); Optional max = fruits.max(comparing(Fruit::getName)); if(max.isPresent()) { String fruitName = max.get().getName(); //grape } Or this another one in which we obtain the first fruit in a stream Stream fruits = asList(new Fruit("apple"), new Fruit("grape")).stream(); Optional first = fruits.findFirst(); if(first.isPresent()) { String fruitName = first.get().getName(); //apple } Ceylon Programming Language and Optional Types Recently I started to play a bit with the Ceylon programming language since I was doing a research for another post that I am planning to publish soon in this blog. I must say I am not a big fan of Ceylon, but still I found particularly interesting that in Ceylon this concept of optional values is taken a bit further, and the language itself offers some syntactic sugar for this idiom. In this language we can mark any type with a ? (question mark) in order to indicate that its type is an optional type. For instance, this find function would be very similar to our original Java version, but this time returning an optional Fruit? reference (1). Also notice that a null value is compatible with the optional Fruit? reference (7). Fruit? find(String name, List fruits){ for(Fruit fruit in fruits) { if(fruit.name == name) { return fruit; } } return null; } And we could use it with this Ceylon code, similar to our last Java snippet in which we used an optional value: List fruits = [Fruit("apple"),Fruit("grape"),Fruit("orange")]; Fruit? fruit = find("lemon", fruits); print((fruit else Fruit("Kiwi")).name); Notice the use of the else keyword here is pretty similar to the method orElse in the Java 8 Optional class. Also notice that the syntax is similar to the declaration of C# nullable types, but it means something totally different in Ceylon. It may be worth mentioning that Kotlin, the programming language under development by Jetbrains, has a similar feature related to null safety (so maybe we are before a trend in programming languages). An alternative way of doing this would have been like this: List fruits = [Fruit("apple"),Fruit("grape"),Fruit("orange")]; Fruit? fruit = find("apple", fruits); if(exists fruit){ String fruitName = fruit.name; print("The found fruit is: " + fruitName); } //else... Notice the use of the exists keyword here (3) serves the same purpose as the isPresent method invocation in the Java Optional class. The great advantage of Ceylon over Java is that they can use this optional type in the APIs since the beginning, within the realm of their language they won't have to deal with incompatibilities, and it can be fully supported everywhere (perhaps their problem will be in their integration with the rest of the Java APIs, but I have not studied this yet). Hopefully, in future releases of Java, this same syntactic sugar from Ceylon and Kotlin will also be made available in the Java programming language, perhaps using, under the hood, this new Optional class introduced in Java 8. Further Reading Java Language Specification The Billion Dollars Mistake Refactoring Catalog Ceylon Programming Language Kotlin Programming Language C# Nullable Types Avoid Using Null (Guava Framework) More Discussion on Java's Optional Java Infinite Streams Java Streams API Preview Java Streams Preview vs .Net High-Order Programming with LINQ
April 17, 2013
by Edwin Dalorzo
· 86,003 Views · 22 Likes
article thumbnail
Stepping Backwards while Debugging: Move To Line
it happens to me many times: i’m stepping with the debugger through my code, and ups! i made one step too far! debugging, and made one step over too far what now? restart the whole debugging session? actually, there is a way to go ‘backwards’ gdb has a ‘reverse debugging’ feature, described here . i’m using the eclipse based codewarrior debugger, and this debug engine is not using gdb. the codewarrior debugger in mcu10.3 supports an eclipse feature: i select a code line in the editor view and use move to line : move to line what it does: it changes the current pc (program counter) of the program to that line: performed move to line now i can continue debugging from that line, e.g. stepping into that function call. yes, this is not true backward debugging. but it is simple and very effective. to perform true backward stepping, the debugger would need to reverse all operations, typically with a rather heavy state machine and data recording. but for the usual case where i simply need to go back a few lines, the ‘move to line’ is perfect. of course there are a few points to consider: this only changes the program counter. any variable changes/etc are not affected or reverted. in case of highly optimized code, there might be multiple sequence points per source line. so doing this for highly optimized code might not work correctly. it works ok within a function. it is not recommended to use it e.g. to set the pc outside of a function. because the context/stack frame is not set up. i use the ‘move to line’ frequently to ‘advance’ the program execution. e.g. to bypass some long sequences i’m not interested in, or to get out of an ‘endless’ loop. the same ‘move to line’ as available while doing assembly stepping too. see this post for details. happy line moving
April 15, 2013
by Erich Styger
· 9,870 Views
article thumbnail
ActiveMQ and .NET combined!
ActiveMQ is one of the most popular messaging frameworks. For sure the most popular open source framework. Many people think that ActiveMQ works only with Java and this is not true at all. ActiveMQ can work with almost every popular language (including JavaScript!) through numerous protocols which it supports. Today I will show you how to use ActiveMQ in .NET-based solutions. Project setup Using VS 2010's Extension Manger I installed NuGet Package Manager. After installation and VS 2010 restart, I created a project called ActiveMQNMS. I right-clicked it and selected "Manage NuGet packages...". In the search field I typed: "ActiveMQ". There was a package called Apache.NMS.ActiveMQ. I installed it. (Note: ActiveMQ has one dependency - Apache.NMS package. The NMS package provides a unified API for working with different messaging frameworks and providers.) Starting ActiveMQ I already had ActiveMQ installed on my machine. If you don't have one, download it from http://activemq.apache.org. The default instance listens on 61616 port. However, mine is listening on 62626. If you want to run my code, please remember to change the port. To start ActiveMQ I executed: activemq-5.5.0\bin\activemq Depending on configured ports, you can use ActiveMQ web console to manage your queues, topics, subscribers, connections, embedded Apache Camel, etc. I'm using 8282 port, and the console URL is: http://localhost:8282/admin. Test stub In general the .NET API is almost a copy of the Java API. So if you're familiar with JMS and/or ActiveMQ you don't need any documentation. Please note TestIntialize and TestCleanup methods. using System; using Apache.NMS; using Apache.NMS.ActiveMQ; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ActiveMQNMS { [Serializable] public class Person { public string FirstName { get; set; } public string LastName { get; set; } } [TestClass] public class ActiveMqTest { private IConnection _connection; private ISession _session; private const String QUEUE_DESTINATION = "DotNet.ActiveMQ.Test.Queue"; [TestInitialize] public void TestInitialize() { IConnectionFactory factory = new ConnectionFactory("tcp://localhost:62626"); _connection = factory.CreateConnection(); _connection.Start(); _session = _connection.CreateSession(); } [TestCleanup] public void TestCleanup() { _session.Close(); _connection.Close(); } } } Writing Producer Here is the producer: [TestMethod] public void TestA() { IDestination dest = _session.GetQueue(QUEUE_DESTINATION); using (IMessageProducer producer = _session.CreateProducer(dest)) { var person = new Person { FirstName = "Łukasz", LastName = "Budnik" }; var objectMessage = producer.CreateObjectMessage(person); producer.Send(objectMessage); } } Run the test and refresh "Queues" list in ActiveMQ web console. You should see DotNet.ActiveMQ.Test.Queue queue with 1 enqueued and pending message. Purge the queue by hitting the purge link or you simply delete it. Writing Consumer Now we have to consume the message. Here is the code: [TestMethod] public void TestB() { Person person = null; IDestination dest = _session.GetQueue(QUEUE_DESTINATION); using (IMessageConsumer consumer = _session.CreateConsumer(dest)) { IMessage message; while ((message = consumer.Receive(TimeSpan.FromMilliseconds(2000))) != null) { var objectMessage = message as IObjectMessage; if (objectMessage != null) { person = objectMessage.Body as Person; if (person != null) { Assert.AreEqual("Łukasz", person.FirstName); Assert.AreEqual("Budnik", person.LastName); } } else { Assert.Fail("Object Message is null"); } } } if (person == null) { Assert.Fail("Person object is null"); } } Run tests. Refresh "Queues" tab in ActiveMQ web console. You should see 1 message enqueued and 1 message dequeued. As expected. Summary That's all. Simple, isn't it? ActiveMQ works very, very nicely with .NET. I have to find some performance comparison for ActiveMQ and MS or pure .C#/NET messaging frameworks. Or maybe you have it? Please share. cheers, Łukasz
April 15, 2013
by Łukasz Budnik
· 29,412 Views
article thumbnail
Introduction to SmartSVN
SmartSVN is a powerful and easy-to-use graphical client for Apache Subversion. There are several clients for Subversion, but here are just a few reasons you should try SmartSVN: It’s cross-platform – SmartSVN runs on Windows, Linux and Mac OS X, so you can continue using the operating system (OS) that works the best for you. It can also be integrated into your OS, via Mac’s Finder Integration or Windows Shell. Everything you need, out of the box – SmartSVN comes complete with all the tools you need to manage your Subversion projects: Conflict solver – this feature combines the freedom of a general, three-way-merge with the ability to detect and resolve any conflicts that occur during the development lifecycle. File compare – this allows you to make inner-line comparisons and directly edit the compared files. Built-in SSH client – allows users to access servers using the SSH protocol. This security-conscious protocol encrypts every piece of communication between the client and the server, for additional protection. A complete view of your project at a glance – the most important files (such as conflicted, modified or missing files) are placed at the top of the file list. SmartSVN also highlights which directories contain local modifications, which directories have been changed in the repository, and whether individual files have been modified locally or in the central repo. This makes it easy to get a quick overview of the state of your project. Fully customizable – maximize productivity by fine-tuning your SmartSVN installation to suit your particular needs: Change keyboard shortcuts, write your own plugin with the SmartSVN API, group revisions to personalize your display, create Change Sets, and alter the context menus and toolbars to suit you. You can learn more about customizing SmartSVN at our ‘5 Ways to Customize SmartSVN’ blog post. Comprehensive bug tracker support – Trac and JIRA are both fully supported. Multitude of support options – SmartSVN users have access to a range of free support, from refcards to blogsand documentation, the SmartSVN forum and a Twitter account maintained by our open source experts. If you need extra support with your SmartSVN installation, expert email support is included with SmartSVN Professional licenses. Want to learn more about SmartSVN? On April 18th, WANdisco will be be holding a free ‘Introduction to SmartSVN’ webinar covering everything you need to get off to a great start with this popular client: Repository basics Checkouts, working folders, editing files and commits Reporting on changes Simple branching Simple merging This webinar is free so register now.
April 13, 2013
by Jessica Thornsby
· 6,595 Views
article thumbnail
Java Lambda Expressions Basics
Learn about Java Lambda essentials, including basics and examples.
April 13, 2013
by Edwin Dalorzo
· 293,458 Views · 24 Likes
article thumbnail
Predicate and Consumer Interface in java.util.function package in Java 8
Here's how to properly use the Predicate and Consumer interfaces in Java 8.
April 11, 2013
by Mohamed Sanaulla
· 39,613 Views · 17 Likes
article thumbnail
Getting Rid of Boilerplate Code with Java Lambda Expressions
As I have mentioned in a previous post, there is nothing we can do with lambda expressions that we could not do without them. Basically because we can implement a similar idiom in Java using anonymous classes. The problem is that anonymous classes require a lot of boilerplate code. To demonstrate the value of lambda expressions as a tool to achieve more succinct code in this post I will develop some classical high-order functions from scratch. Filtering Let’s consider the existence of an interface called Predicate defined as follows: interface Predicate { public boolean test(T t); } And now, let’s say we would like to use the Predicate interface to filter the elements of any given list based on a given predicate. So, we could define something as follows: static List filter(Predicate predicate, List source) { List destiny = new ArrayList<>(); for(T item : source) { if(predicate.test(item)){ destiny.add(item); } } return destiny; } Now, consider that we had a list of numbers, and we would like to filter only those that are odd. Traditionally, in Java, we would use an anonymous class to define the predicate, something like this: List numbers = asList(1,2,3,4,5,6,7,8,9); List onlyOdds = filter(new Predicate(){ @Override public boolean test(Integer n) { return n % 2 != 0; } }, numbers); But consider all the boilerplate code that was necessary here to simply say that we would like to take a value n and check if it is an odd number. Clearly this does not look good. In Java 8, we could get rid of all this mess by simply implementing our predicate using a lambda expression, as follows: List numbers = asList(1,2,3,4,5,6,7,8,9); List onlyOdds = filter(n –> n % 2 !=0, numbers); Here, the lambda expression will be evaluated to an instance of the type Predicate, its argument n, corresponds to the argument expected by its method test, and the body of the expressions represents the implementation of the method. Mapping Let’s consider now the existence of an interface Function defined as follows: interface Function { public R apply(T t); } And now, let’s say we would like to use this functional interface to transform the elements of a list from one value to another. So, we could define a method as follows: static List map(Function function, List source){ List destiny = new ArrayList<>(); for(T item : source) { R value = function.apply(item); destiny.add(value); } return destiny; } Now, consider that we had a list of strings representing numbers and we would like to convert them to their corresponding integer values. Once again, in the traditional model we could use Java anonymous classes for this, like so: List digits = asList("1","2","3","4","5","6","7","8","9"); List numbers = map(new Function digits = asList("1","2","3","4","5","6","7","8","9"); List numbers = map(s –> Integer.valueOf(s), digits); This is clearly much better. Once again, the lambda expression evaluates to an instance of the type Function where s represents the argument for its function apply and the body of the lambda expression represents what the function would return in its body. Reducing Let’s consider now the existence of an interface BinaryOperator defined as follows: interface BinaryOperator { public T apply(T left, T right); } And now we would like to use this functional interface to reduce the values from a list to a single value. So, we could use it as follows: static T reduce(BinaryOperator operator,T seed, List source){ for(T item: source) { seed = operator.apply(seed, item); } return seed; } Consider now that we have a list of numbers and we would like to obtain to summation of them all. Once more, if we intend to use this code as we traditionally have done before the release of Java 8 we would be forced to to following verbose definition, as follows: List numbers = asList(1,2,3,4,5); Integer sum = reduce(new BinaryOperator() { @Override public Integer apply(Integer left, Integer right){ return left + right; } },0,numbers); This code can be greatly simplified by the use of a lambda expression, as follows: List numbers = asList(1,2,3,4,5); Integer sum = reduce( (x,y) –> x + y, 0, numbers); Where (x,y) correspond to the two arguments left and right that the function apply receives, and the body of the expressions would be what it would return. Notice that, since in this case we have to specify two arguments, the lambda expressions is required to specify them within parenthesis, otherwise the compiler could determine which arguments are for the lambda expression and which are for the reduce method. Consuming Let’s consider now the existence of a functional interface Consumer, defined as follows: interface Consumer { public void accept(T t); } Now we could use implementations of this interface to consume the elements of a list and do something with them, like printing them to the main output or sending them over the network, or whatever we could consider appropriate. For this example, let’s just print them to the output: static void forEach(Consumer consumer, List source) { for(T item: source) { consumer.accept(item); } } Look at all the boilerplate code necessary to create a consumer to simply print all the elements of a list: List numbers = asList(1,2,3,4,5); forEach(new Consumer(){ @Override public void accept(Integer n) { System.out.println(n); } },numbers); However, now we could use a simple lambda expression to implement equivalent functionality as follows: List numbers = asList(1,2,3,4,5); forEach(n –> { System.out.println(n); }, numbers); The syntax differs a bit from the previous cases because in this case the method we intend to implement through the lambda expression returns void, and that is why we use a code block to signify that the type of the lambda expression is also void. Producing Let’s consider now the existence of a functional interface Supplier as follows: interface Supplier { public T get(); } A classical idiom is to use this type of interface to encapsulate an expensive calculation and differ its evaluation until needed, something typically known as lazy evaluation. For example: public static int generateX() { return 0; } public static int generateY() { //some expensive calculation here return 1; } public static int calculate(Supplier thunkOfX, Supplier thunkOfY) { int x = thunkOfX.get(); if(x==0) return 0; else return x + thunkOfY.get(); } By means of passing two suppliers here we defer the evaluation of x and y until needed. As you can see, if x is equal to 0, y is never needed. So, by using this idiom we avoid spending a lot of time in a expensive calculation unnecessarily. Before lambda expressions, the invocation of calculation would have implied a lot of boilerplate code as follows: calculate(new Supplier() { @Override public Integer get() { return generateX(); } }, new Supplier() { @Override public Integer get() { return generateY(); } }); However, using lambda expressions, this a one-liner: calculate( () –> generateX(), () –> generateY() ); Clearly this is much better. Summary of Lambda Syntax So, these are different ways to define lambda expressions: Predicate isOdd = n –> n % 2 == 0; Function atoi = s –> Integer.valueOf(s); BinaryOperator product = (x, y) –> x * y Comparator maxInt = (x,y) –> x > y ? x : y; Consumer printer = s –> { System.out.println(s); }; Supplier producer = () –> "Hello World"; Runnable task = () –> { System.out.println("I am a runnable task"); }; In summary, lambda expressions are a great tool to get rid of all the boilerplate required by the clunky Java syntax of anonymous classes. The new API for Streams makes extensive use of this new syntax: int oddSum = asList("1","2","3","4","5").stream() .map(n –> Integer.valueOf(n)) .filter(n –> n % 2 != 0) .reduce(0, (x,y) –> x + y); // 9
April 10, 2013
by Edwin Dalorzo
· 6,937 Views
article thumbnail
Java Lambda Expressions vs Method References
Now we can use lambda expressions to implement functional interfaces as we have seen in previous posts, but the lambda expressions are not the only mechanism we can use for this purpose. Particularly where there are preexisting code that we would like to reuse we can simplify the implementation of the functional interface by using method references. Static Method References First, consider the existence of a functional interface Predicate as follows: public interface Predicate { public void test(T t); } And let’s say that we had a method to filter elements out of a list using this predicate, as follows: static List filter(Predicate predicate, List source) { List destiny = new ArrayList<>(); for (T item : source) { if(predicate.test(item)){ destiny.add(item); } } return destiny; } Finally, let’s say we had a class containing a set of static method predicates which we had defined in the past, prior to the existence of the Java 8. Something as follows: static class IntPredicates { public static boolean isOdd(Integer n) { return n % 2 != 0; } public static boolean isEven(Integer n) { return n % 2 == 0; } public static boolean isPositive(Integer n) { return n >= 0; } } Now, one way to implement a predicate that could reuse our static methods would be through the use of lambda expressions, like this: Predicate isOdd = n -> IntPredicates.isOdd(n); Predicate isEven = n -> IntPredicates.isEven(n); However, we can clearly see that the signature of the static predicate methods corresponds perfectly with the signature of the test method for integer predicates. So, an alternative way to implement the functional interface in this case is through a static method reference, as follows: Predicate isOdd = IntPredicates::isOdd; Predicate isEven = IntPredicate::isEven; Notice the use of double colon :: here. We are not invoking the method, we are just referencing its name. We could now use this technique to filter a list of numbers that satisfy any of these predicates, something like this: List numbers = asList(1,2,3,4,5,6,7,8,9); List odds = filter(IntPredicates::isOdd, numbers); List evens = filter(IntPredicates::isEven, numbers); So, as we can see, we could implement the functional interfaces in this case using both: lambda expressions and method references, but the syntax with the static method references was more succinct. Constructor Method References Let’s consider now the existence of a functional interface named Function, as follows: public interface Function { public R apply(T t); } Based on it, we could define a method map, that converts the elements from a source list from certain value T to certain value R, as follows: static List map(Function function, List source) { List destiny = new ArrayList<>(); for (T item : source) { R value = function.apply(item); destiny.add(value); } return destiny; } Now imagine that we had a list of strings containing numbers that we would like to transform to integer values. We could do it using a lambda expression to provide an implementation for the Function interface, more or less like this: List digits = asList("1","2","3","4","5"); List numbers = map(s -> new Integer(s), digits); However, we can clearly infer that the constructor Integer(String) has the same signature as the apply method in the Function reference required here, namely, it receives a string as argument and returns an integer. So, in this case we simplify the implementation of the functional interface by means of using a constructor reference, as follows: List digits = asList("1","2","3","4","5"); List numbers = map(Integer::new, digits); This conveys the same meaning: take a string and make me an integer out of it. It is the perfect task for our Integer(String) constructor. Instance Method Reference to Arbitrary Objects Consider now the existence of a class named Jedi, defined as follows: public class Jedi { private String name; private int power; public Jedi(String name, int power){ this.name = name; this.power = power; } public String getName() { return name; } public int getPower() { return power; } //equals,hashCode,toString } Now, consider that we had a list of jedis, and we would like to use our previous function map to extract the name from every jedi and generate a list of names out of the list of jedis. Somewhat like this, using lambda expressions: List jedis = asList(new Jedi("Obi-wan", 80), new Jedi("Anakin", 25), new Jedi("Yoda", 500)); List names = map(jedi -> jedi.getName() , jedis); The interesting observation here is that the parameter jedi is the argument for the apply method in the Function reference. And we use that reference to a jedi to invoke on it the method getName. In other words, we invoke a method on the reference we receive as argument. So, we could simplify this implementation by using an instance method reference as follows: List jedi = asList(new Jedi("Obi-wan", 80), new Jedi("Anakin", 25), new Jedi("Yoda", 500)); List names = map(Jedi::getName, jedi); Again, the interesting aspect of this type of method reference is that the method getName is an instance method. Therefore, the target of its invocation must be an instance, which in this case is an arbitrary object being provided as the argument for the method apply in the Function interface definition. Instance Method Reference to a Specific Object Let’s consider the existence of functional interface named Consumer, as follows public interface Consumer { public void accept(T t); } And let’s define a method capable of using a consumer to consume all the elements of a given list, like this: static void forEach(Consumer consumer, List source){ for (T item : source) { consumer.accept(item); } } Imagine that now we would like to print all the elements contained in a list, and for that purpose we could define a consumer using a lambda expressions: List numbers = asList(1,2,3,4,5,6,7,8,9); forEach(n -> { System.out.println(n); }, numbers); However, we could also make the observation that the method println has the same signature that our Consumer has, it receives an integer and does something with it, in this case it prints it to the main output. However, we cannot specify that this is an arbitrary instance method reference by saying PrintStream::println, because in this case the Consumer interface method accept does not receive as one of its arguments the PrintStream object on which we may want to invoke the method println. Conversely, we already know which is the target object on which we would like to invoke the method: we can see that every time we would like to invoke it on a specific reference, in this case the object System.out. So, we could implement our functional interface using an instance method reference to a specific object as follows: List numbers = asList(1,2,3,4,5,6,7,8,9); forEach(System.out::println, numbers); In summary, there are circumstances in which we would like to use some preexisting code as the implementation for a functional interface, in those case we could use one of several variants of method references instead of a more verbose lambda expression.
April 9, 2013
by Edwin Dalorzo
· 79,534 Views · 5 Likes
article thumbnail
Capture a Signature on iOS
Originally authored by Jason Harwig The Square Engineering Blog has a great article on Smoother Signatures for Android, but I didn't find anything specifically about iOS. So, what is the best way to capture a users signature on an iOS device? Although I didn't find any articles on signature capture, there are good implementations on the App Store. My target user experience was the iPad application Paper by 53, a drawing application with beautiful and responsive brushes. All code is available in the Github repository: SignatureDemo. Connecting the Dots The simplest approach is to capture the touches and connect them with straight lines. In the initializer of a UIView subclass, create the path and gesture recognizer to capture touch events. // Create a path to connect lines path = [UIBezierPath bezierPath]; // Capture touches UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)]; pan.maximumNumberOfTouches = pan.minimumNumberOfTouches = 1; [self addGestureRecognizer:pan]; Capture the pan events into a bézier path by connecting the points with lines. - (void)pan:(UIPanGestureRecognizer *)pan { CGPoint currentPoint = [pan locationInView:self]; if (pan.state == UIGestureRecognizerStateBegan) { [path moveToPoint:currentPoint]; } else if (pan.state == UIGestureRecognizerStateChanged) [path addLineToPoint:currentPoint]; [self setNeedsDisplay]; } Stroke the path - (void)drawRect:(CGRect)rect { [[UIColor blackColor] setStroke]; [path stroke]; } An example "J" character rendered using this technique reveals some issues. At slow velocities iOS captures enough touch resolution that the lines aren't noticeable, but faster movement shows large gaps between touches that accentuates the lines. The 2012 Apple Developer Conference included a session Building Advanced Gesture Recognizers that addresses this issue using math. Quadratic Bézier Curves Instead of connected lines between the touch points, quadratic bézier curves connect the points using the technique discussed in the aforementioned WWDC session (Seek to 42:15.) Connect the touch points with a quadratic curve using the touch points as the control points and the mid points as start and end. Adding quadratic curves to the previous code requires the storing the previous touch point, so add an instance variable for that. CGPoint previousPoint; Create a function to calculate the midpoint of two points. static CGPoint midpoint(CGPoint p0, CGPoint p1) { return (CGPoint) { (p0.x + p1.x) / 2.0, (p0.y + p1.y) / 2.0 }; } Update the pan gesture handler to add quadratic curves instead of straight lines - (void)pan:(UIPanGestureRecognizer *)pan { CGPoint currentPoint = [pan locationInView:self]; CGPoint midPoint = midpoint(previousPoint, currentPoint); if (pan.state == UIGestureRecognizerStateBegan) { [path moveToPoint:currentPoint]; } else if (pan.state == UIGestureRecognizerStateChanged) { [path addQuadCurveToPoint:midPoint controlPoint:previousPoint]; } previousPoint = currentPoint; [self setNeedsDisplay]; } Not much code and already we see a big difference. The touch points are no longer visible, but it looks a little bland when drawing a signature. Every curve is the same width, which doesn't match the physics of a real pen. Variable Stroke Width The width can be varied based on the touch velocity to create a more natural stroke. The UIPanGestureRecognizer already includes a method called velocityInView: that returns the current touch velocity as a CGPoint. To render a stroke of varying width, I switched to OpenGL ES and a technique called tesselation to convert the stroke into triangles – specifically, triangle strips (OpenGL has support for drawing lines, but iOS doesn't support variable line widths with smoothing.) The quadratic points along a curve also need to be calculated, but is beyond the scope of this article. Check the source on github for details. Given two points, a perpendicular vector is calculated and its magnitude set to half the current thickness. Given the nature of GL_TRIANGLE_STRIP only two points are needed to create the next rectangle segment with two triangles. Here is an example of the final output using quadratic bézier curves, and velocity based stroke thickness creating a visually appealing and natural signature.
April 8, 2013
by Scott Leberknight
· 20,814 Views
article thumbnail
Covariance and Contravariance In Java
I have found that in order to understand covariance and contravariance a few examples with Java arrays are always a good start. Arrays Are Covariant Arrays are said to be covariant which basically means that, given the subtyping rules of Java, an array of type T[] may contain elements of type T or any subtype of T. For instance: Number[] numbers = newNumber[3]; numbers[0] = newInteger(10); numbers[1] = newDouble(3.14); numbers[2] = newByte(0); But not only that, the subtyping rules of Java also state that an array S[] is a subtype of the array T[] if S is a subtype of T, therefore, something like this is also valid: Integer[] myInts = {1,2,3,4}; Number[] myNumber = myInts; Because according to the subtyping rules in Java, an array Integer[] is a subtype of an array Number[] because Integer is a subtype of Number. But this subtyping rule can lead to an interesting question: what would happen if we try to do this? myNumber[0] = 3.14; //attempt of heap pollution This last line would compile just fine, but if we run this code, we would get an ArrayStoreException because we’re trying to put a double into an integer array. The fact that we are accessing the array through a Number reference is irrelevant here, what matters is that the array is an array of integers. This means that we can fool the compiler, but we cannot fool the run-time type system. And this is so because arrays are what we call a reifiable type. This means that at run-time Java knows that this array was actually instantiated as an array of integers which simply happens to be accessed through a reference of type Number[]. So, as we can see, one thing is the actual type of the object, an another thing is the type of the reference that we use to access it, right? The Problem with Java Generics Now, the problem with generic types in Java is that the type information for type parameters is discarded by the compiler after the compilation of code is done; therefore this type information is not available at run time. This process is called type erasure. There are good reasons for implementing generics like this in Java, but that’s a long story, and it has to do with binary compatibility with pre-existing code. The important point here is that since at run-time there is no type information, there is no way to ensure that we are not committing heap pollution. Let’s consider now the following unsafe code: List myInts = newArrayList(); myInts.add(1); myInts.add(2); List myNums = myInts; //compiler error myNums.add(3.14); //heap polution If the Java compiler does not stop us from doing this, the run-time type system cannot stop us either, because there is no way, at run time, to determine that this list was supposed to be a list of integers only. The Java run-time would let us put whatever we want into this list, when it should only contain integers, because when it was created, it was declared as a list of integers. That’s why the compiler rejects line number 4 because it is unsafe and if allowed could break the assumptions of the type system. As such, the designers of Java made sure that we cannot fool the compiler. If we cannot fool the compiler (as we can do with arrays) then we cannot fool the run-time type system either. As such, we say that generic types are non-reifiable, since at run time we cannot determine the true nature of the generic type. Evidently this property of generic types in Java would have a negative impact on polymorphism. Let’s consider now the following example: staticlongsum(Number[] numbers) { longsummation = 0; for(Number number : numbers) { summation += number.longValue(); } returnsummation; } Now we could use this code as follows: Integer[] myInts = {1,2,3,4,5}; Long[] myLongs = {1L, 2L, 3L, 4L, 5L}; Double[] myDoubles = {1.0, 2.0, 3.0, 4.0, 5.0}; System.out.println(sum(myInts)); System.out.println(sum(myLongs)); System.out.println(sum(myDoubles)); But if we attempt to implement the same code with generic collections, we would not succeed: staticlongsum(List numbers) { longsummation = 0; for(Number number : numbers) { summation += number.longValue(); } returnsummation; } Because we we would get compiler errors if you try to do the following: List myInts = asList(1,2,3,4,5); List myLongs = asList(1L, 2L, 3L, 4L, 5L); List myDoubles = asList(1.0, 2.0, 3.0, 4.0, 5.0); System.out.println(sum(myInts)); //compiler error System.out.println(sum(myLongs)); //compiler error System.out.println(sum(myDoubles)); //compiler error The problem is that now we cannot consider a list of integers to be subtype of a list of numbers, as we saw above, that would be considered unsafe for the type system and compiler rejects it immediately. Evidently, this is affecting the power of polymorphism and it needs to be fixed. The solution consists in learning how to use two powerful features of Java generics known as covariance and contravariance. Covariance For this case, instead of using a type T as the type argument of a given generic type, we use a wildcard declared as ? extends T, where T is a known base type. With covariance we can read items from a structure, but we cannot write anything into it. All these are valid covariant declarations. List myNums = newArrayList(); List myNums = newArrayList(); List myNums = newArrayList(); And we can read from our generic structure myNums by doing: Number n = myNums.get(0); Because we can be sure that whatever the actual list contains, it can be upcasted to a Number (after all anything that extends Number is a Number, right?) However, we are not allowed to put anything into a covariant structure. myNumst.add(45L); //compiler error This would not be allowed because the compiler cannot determine what is the actual type of the object in the generic structure. It can be anything that extends Number (like Integer, Double, Long), but the compiler cannot be sure what, and therefore any attempt to retrieve a generic value is considered an unsafe operation and it is immediately rejected by the compiler. So we can read, but not write. Contravariance For contravariance we use a different wildcard called ? super T, where T is our base type. With contravariance we can do the opposite. We can put things into a generic structure, but we cannot read anything out of it. In this case, the actual nature of the object is List of Object, and through contravariance, we can put a Number in it, basically because a Number has Object as its common ancestor. As such, all numbers are also objects, and therefore this is valid. However, we cannot safely read anything from this contravariant structure assuming that we will get a number. Number myNum = myNums.get(0); //compiler-error As we can see, if the compiler allowed us to write this line, we would get a ClassCastException at run time. So, once again, the compiler does not run the risk of allowing this unsafe operation and rejects it immediately. Get/Put Principle In summary, we use covariance when we only intend to take generic values out of a structure. We use contravariance when we only intend to put generic values into a structure and we use an invariant when we intend to do both. The best example I have is the following that copies any kind of numbers from one list into another list. It only gets items from the source, and it only puts items in the destiny. publicstaticvoidcopy(List source, List destiny) { for(Number number : source) { destiny.add(number); } } Thanks to the powers of covariance and contravariance this works for a case like this: List myInts = asList(1,2,3,4); List myDoubles = asList(3.14, 6.28); List
April 8, 2013
by Edwin Dalorzo
· 139,838 Views · 28 Likes
article thumbnail
Function Interface- A Functional Interface in the java.util.function Package in Java 8
I had previously written about functional interfaces and their usage. If you are exploring the APIs to be part of Java 8 and especially those APIs which support lambda expressions you will find few interfaces like- Function, Supplier, Consumer, Predicate and others which are all part of the java.util.function package, being used extensively. These interfaces have one abstract method, which is overridden by the lambda expression defined. In this post I will pick Function interface to explain about it in brief and it is one of the interfaces present in java.util.function package. Function interface has two methods: R apply(T t) – Compute the result of applying the function to the input argument default ‹V› Function‹T,V› – Combine with another function returning a function which performs both functions. In this post I would like to write about the apply method, creating APIs which accept these interfaces and parameters and then invoke their corresponding methods. We will also look at how the caller of the API can pass in a lambda expression in place of an implementation of the interface. Apart from passing a lambda expression, the users of the API can also pass method references, about which I havent blogged yet. Function interface is uses in cases where you want to encapsulate some code into a method which accepts some value as an input parameter and then returns another value after performing required operations on the input. The input parameter type and the return type of the method can either be same or different. Lets look at an API which accepts an implementation of Function interface: public class FunctionDemo { //API which accepts an implementation of //Function interface static void modifyTheValue(int valueToBeOperated, Function function){ int newValue = function.apply(valueToBeOperated); /* * Do some operations using the new value. */ System.out.println(newValue); } } Now lets look at the code which invokes this API: public static void main(String[] args) { int incr = 20; int myNumber = 10; modifyTheValue(myNumber, val-> val + incr); myNumber = 15; modifyTheValue(myNumber, val-> val * 10); modifyTheValue(myNumber, val-> val - 100); modifyTheValue(myNumber, val-> "somestring".length() + val - 100); } You can see that the lambda expressions being created accept one parameter and return some value. I will update soon about the various APIs which use this Function interface as a parameter. Meanwhile the complete code is: public class FunctionDemo { public static void main(String[] args) { int incr = 20; int myNumber = 10; modifyTheValue(myNumber, val-> val + incr); myNumber = 15; modifyTheValue(myNumber, val-> val * 10); modifyTheValue(myNumber, val-> val - 100); modifyTheValue(myNumber, val-> "somestring".length() + val - 100); } //API which accepts an implementation of //Function interface static void modifyTheValue(int valueToBeOperated, Function function){ int newValue = function.apply(valueToBeOperated); /* * Do some operations using the new value. */ System.out.println(newValue); } } and the output is: 30 150 -85 -75 In the coming posts I will try to explore the other interfaces present in java.util.function package. Note: The above code was compiled using the JDK downloaded from here and Netbeans 8 nightly builds.
April 6, 2013
by Mohamed Sanaulla
· 12,514 Views
article thumbnail
Java EE 7 and EJB 3.2 support in JBoss AS 8
Some of you might be aware that the Public Final Draft version of Java EE 7 spec has been released. Among various other new things, this version of Java EE, brings in EJB 3.2 version of the EJB specification. EJB 3.2 has some new features compared to the EJB 3.1 spec. I'm quoting here the text present in the EJB 3.2 spec summarizing what's new: The Enterprise JavaBeans 3.2 architecture extends Enterprise JavaBeans to include the following new functionality and simplifications to the earlier EJB APIs: Support for the following features has been made optional in this release and their description is moved to a separate EJB Optional Features document: EJB 2.1 and earlier Entity Bean Component Contract for Container-Managed Persistence EJB 2.1 and earlier Entity Bean Component Contract for Bean-Managed Persistence Client View of an EJB 2.1 and earlier Entity Bean EJB QL: Query Language for Container-Managed Persistence Query Methods JAX-RPC Based Web Service Endpoints JAX-RPC Web Service Client View Added support for local asynchronous session bean invocations and non-persistent EJB Timer Service to EJB 3.2 Lite. Removed restriction on obtaining the current class loader; replaced ‘must not’ with ‘should exercise caution’ when using the Java I/O package. Added an option for the lifecycle callback interceptor methods of stateful session beans to be executed in a transaction context determined by the lifecycle callback method's transaction attribute. Added an option to disable passivation of stateful session beans. Extended the TimerService API to query all active timers in the same EJB module. Removed restrictions on javax.ejb.Timer and javax.ejb.TimerHandle references to be used only inside a bean. Relaxed default rules for designating implemented interfaces for a session bean as local or as remote business interfaces. Enhanced the list of standard activation properties. Enhanced embeddable EJBContainer by implementing AutoClosable interface. As can be seen, some of the changes proposed are minor. But there are some which are useful major changes. We'll have a look at a couple of such changes in this article. 1) New API TimerService.getAllTimers() EJB 3.2 version introduces a new method on the javax.ejb.TimerService interface, named getAllTimers. Previously the TimerService interface had (and still has) a getTimers method. The getTimers method was expected to return the active timers that are applicable for the bean on whose TimerService, the method had been invoked (remember: there's one TimerService per EJB). In this new EJB 3.2 version, the newly added getAllTimers() method is expected to return all the active timers that are applicable to *all beans within the same EJB module*. Typically, an EJB module corresponds to a EJB jar, but it could also be a .war deployment if the EJBs are packaged within the .war. This new getAllTimers() method is a convenience API for user applications which need to find all the active timers within the EJB module to which that bean belongs. 2) Ability to disable passivation of stateful beans Those familiar with EJBs will know that the EJB container provides passivation (storing the state of the stateful bean to some secondary store) and activation (loading the saved state of the stateful bean) capability to stateful beans. However, previous EJB versions didn't have a portable way of disabling passivation of stateful beans, if the user application desired to do that. The new EJB 3.2 version introduces a way where the user application can decide whether the stateful bean can be passivated or not. By default, the stateful bean is considered to be "passivation capable" (like older versions of EJB). However, if the user wants to disable passivation support for certain stateful bean, then the user has the option to either disable it via annotation or via the ejb-jar.xml deployment descriptor. Doing it the annotation way is as simple as setting the passivationCapable attribute on the @javax.ejb.Stateful annotation to false. Something like: @javax.ejb.Stateful(passivationCapable=false) // the passivationCapable attribute takes a boolean value public class MyStatefulBean { .... } Doing it in the ejb-jar.xml is as follows: foo-bar-bean org.myapp.FooBarStatefulBean Stateful false ... Two important things to note in that ejb-jar.xml are the version=3.2 attribute (along with the http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd schema location) on the ejb-jar root element and the passivation-capable element under the session element. So, using either of these approaches will allow you to disable passivation on stateful beans, if you want to do so. Java EE 7 and EJB 3.2 support in JBoss AS8: JBoss AS8 has been adding support for Java EE 7 since the Public Final Draft version of the spec has been announced. Support for EJB 3.2 is already added and made available. Some other Java EE 7 changes have also made it to the latest JBoss AS 8 builds. To keep track of the Java EE 7 changes in JBoss AS8, keep an eye on this JIRA https://issues.jboss.org/browse/AS7-6553. To use the already implemented features of Java EE 7 in general or EJB 3.2 in particular, you can download the latest nightly build/binary of JBoss AS from here. Give it a try and let us know how it goes. For any feedback, questions or if you run into any kind of issues, feel free to open a discussion thread in our user forum here.
April 5, 2013
by Jaikiran Pai
· 8,815 Views
article thumbnail
How to use Mock/Stub in Spring Integration Tests
Generally, you pick up a subset of components in some integration tests to check if they are glued as expected. To achieve this, they are usually really invoked, but sometimes, it is too expensive to do so. For example, Component A invokes Component B, and Component B has a dependency on an external system which does not have a test server. We really want to verify the configurations, it seems the only way is replacing Component B with test double after wiring Component A and B. Let's start with Strategy A: Manual Injecting @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:config.xml") public class SomeAppIntegrationTestsUsingManualReplacing { private Mockery context = new JUnit4Mockery(); (1) private SomeInterface mock = context.mock(SomeInterface.class); (2) @Resource(name = "someApp") private SomeApp someApp; (3) @Before public void replaceDependenceWithMock() { someApp.setDependence(mock); (4) } @DirtiesContext @Test public void returnsHelloWorldIfDependenceIsAvailable() throws Exception { context.checking(new Expectations() { { allowing(mock).isAvailable(); will(returnValue(true)); (5) } }); String actual = someApp.returnHelloWorld(); assertEquals("helloWorld", actual); context.assertIsSatisfied(); (6) } } We get a spring bean someApp(Component A in this case), and it has a denpendence on SomeInterface's(Component B in this case). We inject mock (declare and init at step 4) to someApp, thus the test passes without sending request to the external system. The context.assertIsSatisfied()(at step 6 ) is very important as we use SpringJUnit4ClassRunner as junit runner instead of JMock, so you have to explictly assert that all expectations are satisfied. There are two downsides of the previous strategy: Firstly, if there are more than one mock, you have to inject them one by one, which is very tedious especially when you need to inject mocks into serveral spring bean. Secondly, the wiring is not tested. For example, if I forget to write the integration tests using manual inject strategy is not going to tell. Strategy B: Using predefined BeanPostProcessor Spring provides BeanPostProcessor which is very useful when you want to replace some bean after the wiring is done. According to the reference, application context will auto detect all BeanPostProcessor registered in metadata(usually in xml format). public class PredefinedBeanPostProcessor implements BeanPostProcessor { public Mockery context = new JUnit4Mockery(); (1) public SomeInterface mock = context.mock(SomeInterface.class); (2) @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if ("dependence".equals(beanName)) { return mock; } else { return bean; } } } @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:config.xml", "classpath:predefined.xml" }) (1) public class SomeAppIntegrationTestsUsingPredefinedReplacing { @Resource(name = "someApp") private SomeApp someApp; @Resource(name = "predefined") private PredefinedBeanPostProcessor fixture; @Test public void returnsHelloWorldIfDependenceIsAvailable() throws Exception { fixture.context.checking(new Expectations() { { allowing(fixture.mock).isAvailable(); will(returnValue(true)); } }); String actual = someApp.returnHelloWorld(); assertEquals("helloWorld", actual); fixture.context.assertIsSatisfied(); } } Notice there is an extra config xml in which the PredefinedBeanPostProcessor is registered(at step 1). The predefined.xml is placed in src/test/resources/, so it will not be packed into the artifact for production. For each test, using Strategy B requires inputting both a java file and a xml which is quite verbose. Now we have learned the pros and cons of Strategy A and Strategy B. What about a hybrid version -- killing two birds with one stone. Therefore we have the next strategy. Strategy C:Dynamic Injecting public class TestDoubleInjector implements BeanPostProcessor { private static Map MOCKS = new HashMap(); (1) @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (MOCKS.containsKey(beanName)) { return MOCKS.get(beanName); } return bean; } public void addMock(String beanName, Object mock) { MOCKS.put(beanName, mock); } public void clear() { MOCKS.clear(); } } @RunWith(JMock.class) public class SomeAppIntegrationTestsUsingDynamicReplacing { private Mockery context = new JUnit4Mockery(); private SomeInterface mock = context.mock(SomeInterface.class); private SomeApp someApp; private ConfigurableApplicationContext applicationContext; private TestDoubleInjector fixture = new TestDoubleInjector(); (1) @Before public void replaceDependenceWithMock() { fixture.addMock("dependence", mock); (2) applicationContext = new ClassPathXmlApplicationContext(new String[] { "classpath:config.xml", "classpath:dynamic.xml" }); (3) someApp = (SomeApp) applicationContext.getBean("someApp"); } @Test public void returnsHelloWorldIfDependenceIsAvailable() throws Exception { context.checking(new Expectations() { { allowing(mock).isAvailable(); will(returnValue(true)); } }); String actual = someApp.returnHelloWorld(); assertEquals("helloWorld", actual); } @After public void clean() { applicationContext.close(); fixture.clear(); } } The TestDoubleInjector class is an implementation of Monostate pattern. Mocks are added to the static map before the application context being created. When another TestDoubleInjector instance (defined in dynamic.xml) is initiated, it can share the static map for replacement. Just beware to clear the static map after tests. By the way, you could use Stub instead of Mocks with same strategies. Please do not hesitate to contact me if you might have any questions. And I do appreciate it, if you could let me know you have a better idea. Thanks! Resources: http://www.jmock.org http://www.oracle.com/technetwork/articles/entarch/spring-aop-with-ejb5-093994.html(I saw BeanPostProcessor the first time in this post)
April 3, 2013
by Hippoom Zhou
· 51,779 Views · 1 Like
article thumbnail
Promises and Futures in Clojure
Clojure, being designed for concurrency is a natural fit for our Back to the Future series. Moreover futures are supported out-of-the-box in Clojure. Last but not least, Clojure is the first language/library that draws a clear distinction between futures and promises. They are so similar that most platforms either support only futures or combine them. Clojure is very explicit here, which is good. Let's start from promises: Promises Promise is a thread-safe object that encapsulates immutable value. This value might not be available yet and can be delivered exactly once, from any thread, later. If other thread tries to dereference a promise before it's delivered, it'll block calling thread. If promise is already resolved (delivered), no blocking occurs. Promise can only be delivered once and can never change its value once set: (def answer (promise)) @answer (deliver answer 42) answer is a promise var. Trying to dereference it using @answer or (deref answer) at this point will simply block. This or some other thread must first deliver some value to this promise (using deliver function). All threads blocked on deref will wake up and subsequent attempts to dereference this promise will return 42 immediately. Promise is thread safe and you cannot modify it later. Trying to deliver another value to answer is ignored. Futures Futures behave pretty much the same way in Clojure from user perspective - they are containers for a single value (of course it can be a map or list - but it should be immutable) and trying to dereference future before it is resolved blocks. Also just like promises, futures can only be resolved once and dereferencing resolved future has immediate effect. The difference between the two is semantic, not technical. Future represents background computation, typically in a thread pool while promise is just a simple container that can be delivered (filled) by anyone at any point in time. Typically there is no associated background processing or computation. It's more like an event we are waiting for (e.g. JMS message reply we wait for). That being said, let's start some asynchronous processing. Similar to Akka, underlying thread pool is implicit and we simply pass piece of code that we want to run in background. For example to calculate the sum of positive integers below ten million we can say: (let [sum (future (apply + (range 1e7)))] (println "Started...") (println "Done: " @sum) ) sum is the future instance. "Started..." message appears immediately as the computation started in background thread. But @sum is blocking and we actually have to wait a little bit1 to see the "Done: " message and computation results. And here is where the greatest disappointment arrives: neither future nor promise in Clojure supports listening for completion/failure asynchronously. The API is pretty much equivalent to very limited java.util.concurrent.Future. We can create future, cancel it, check whether it is realized? (resolved) and block waiting for a value. Just like Future in Java, as a matter of fact the result of future function even implements java.util.concurrent.Future. As much as I love Clojure concurrency primitives like STM and agents, futures feel a bit underdeveloped. Lack of event-driven, asynchronous callbacks that are invoked whenever futures completes (notice that add-watch doesn't work futures - and is still in alpha) greatly reduces the usefulness of a future object. We can no longer: map futures to transform result value asynchronously chain futures translate list of futures to future of list ...and much more, see how Akka does it and Guava to some extent That's a shame and since it's not a technical difficulty but only a missing API, I hope to see support for completion listeners soon. For completeness here is a slightly bigger program using futures to concurrently fetch contents of several websites, foundation for our web crawling sample: (let [ top-sites `("www.google.com" "www.youtube.com" "www.yahoo.com" "www.msn.com") futures-list (doall ( map #( future (slurp (str "http://" %)) ) top-sites )) contents (map deref futures-list) ] (doseq [s contents] (println s)) ) Code above starts downloading contents of several websites concurrently. map deref waits for all results one after another and once all futures from futures-list all completed, doseq prints the contents (contents is a list of strings). One trap I felt into was the absence of doall (that forces lazy sequence evaluation) in my initial attempt. map produces lazy sequence out of top-sites list, which means future function is called only when given item of futures-list is first accessed. That's good. But each item is accessed for the first time only during (map deref futures-list). This means that while waiting for first future to dereference, second future didn't even started yet! It starts when first future completes and we try to dereference the second one. That means that last future starts when all previous futures are already completed. To cut long story short, without doall that forces all futures to start immediately, our code runs sequentially, one future after another. The beauty of side effects. 1 - BTW (1L to 9999999L).sum in Scala is faster by almost an order of magnitude, just sayin'...
April 1, 2013
by Tomasz Nurkiewicz
· 11,710 Views · 1 Like
article thumbnail
How Does Java Handle Aliasing?
Aliasing means there are multiple aliases to a location that can be updated, and these aliases have different types. In the following example, a and b are two variable names that have two different types A and B. B extends A. B[] b = new B[10]; A[] a = b; a[0] = new A(); b[0].methodParent(); In memory, they both refer to the same location. The pointed memory location are pointed by both a and b. During run-time, the actual object stored determines which method to call. How does Java handle aliasing problem? If you copy this code to your eclipse, there will be no compilation errors. class A { public void methodParent() { System.out.println("method in Parent"); } } class B extends A { public void methodParent() { System.out.println("override method in Child"); } public void methodChild() { System.out.println("method in Child"); } } public class Main { public static void main(String[] args) { B[] b = new B[10]; A[] a = b; a[0] = new A(); b[0].methodParent(); } } But if you run the code, the output would be as follows: Exception in thread “main” java.lang.ArrayStoreException: aliasingtest.A at aliasingtest.Main.main(Main.java:26) The reason is that Java handles aliasing during run-time. During run-time, it knows that the first element should be a B object, instead of A. Therefore, it only runs correctly if it is changed to: B[] b = new B[10]; A[] a = b; a[0] = new B(); b[0].methodParent(); and the output is: override method in Child * original article
March 30, 2013
by Ryan Wang
· 37,162 Views
article thumbnail
HashSet vs. TreeSet vs. LinkedHashSet
in a set, there are no duplicate elements. that is one of the major reasons to use a set. there are 3 commonly used implementations of set in java: hashset, treeset and linkedhashset. when and which to use is an important question. in brief, if we want a fast set, we should use hashset; if we need a sorted set, then treeset should be used; if we want a set that can be read by following its insertion order, linkedhashset should be used. 1. set interface set interface extends collection interface. in a set, no duplicates are allowed. every element in a set must be unique. we can simply add elements to a set, and finally we will get a set of elements with duplicates removed automatically. 2. hashset vs. treeset vs. linkedhashset hashset is implemented using a hash table. elements are not ordered. the add, remove, and contains methods has constant time complexity o(1). treeset is implemented using a tree structure(red-black tree in algorithm book). the elements in a set are sorted, but the add, remove, and contains methods has time complexity of o(log (n)). it offers several methods to deal with the ordered set like first(), last(), headset(), tailset(), etc. linkedhashset is between hashset and treeset. it is implemented as a hash table with a linked list running through it, so it provides the order of insertion. the time complexity of basic methods is o(1). 3. treeset example treeset tree = new treeset(); tree.add(12); tree.add(63); tree.add(34); tree.add(45); iterator iterator = tree.iterator(); system.out.print("tree set data: "); while (iterator.hasnext()) { system.out.print(iterator.next() + " "); } output is sorted as follows: tree set data: 12 34 45 63 now let's define a dog class as follows: class dog { int size; public dog(int s) { size = s; } public string tostring() { return size + ""; } } let's add some dogs to treeset like the following: import java.util.iterator; import java.util.treeset; public class testtreeset { public static void main(string[] args) { treeset dset = new treeset(); dset.add(new dog(2)); dset.add(new dog(1)); dset.add(new dog(3)); iterator iterator = dset.iterator(); while (iterator.hasnext()) { system.out.print(iterator.next() + " "); } } } compile ok, but run-time error occurs: exception in thread "main" java.lang.classcastexception: collection.dog cannot be cast to java.lang.comparable at java.util.treemap.put(unknown source) at java.util.treeset.add(unknown source) at collection.testtreeset.main(testtreeset.java:22) because treeset is sorted, the dog object need to implement java.lang.comparable's compareto() method like the following: class dog implements comparable{ int size; public dog(int s) { size = s; } public string tostring() { return size + ""; } @override public int compareto(dog o) { return size - o.size; } } the output is: 1 2 3 4. hashset example hashset dset = new hashset(); dset.add(new dog(2)); dset.add(new dog(1)); dset.add(new dog(3)); dset.add(new dog(5)); dset.add(new dog(4)); iterator iterator = dset.iterator(); while (iterator.hasnext()) { system.out.print(iterator.next() + " "); } output: 5 3 2 1 4 note the order is not certain. 5. linkedhashset example linkedhashset dset = new linkedhashset(); dset.add(new dog(2)); dset.add(new dog(1)); dset.add(new dog(3)); dset.add(new dog(5)); dset.add(new dog(4)); iterator iterator = dset.iterator(); while (iterator.hasnext()) { system.out.print(iterator.next() + " "); } the order of the output is certain and it is the insertion order. 2 1 3 5 4 6. performance testing the following method tests the performance of the three class on add() method. public static void main(string[] args) { random r = new random(); hashset hashset = new hashset(); treeset treeset = new treeset(); linkedhashset linkedset = new linkedhashset(); // start time long starttime = system.nanotime(); for (int i = 0; i < 1000; i++) { int x = r.nextint(1000 - 10) + 10; hashset.add(new dog(x)); } // end time long endtime = system.nanotime(); long duration = endtime - starttime; system.out.println("hashset: " + duration); // start time starttime = system.nanotime(); for (int i = 0; i < 1000; i++) { int x = r.nextint(1000 - 10) + 10; treeset.add(new dog(x)); } // end time endtime = system.nanotime(); duration = endtime - starttime; system.out.println("treeset: " + duration); // start time starttime = system.nanotime(); for (int i = 0; i < 1000; i++) { int x = r.nextint(1000 - 10) + 10; linkedset.add(new dog(x)); } // end time endtime = system.nanotime(); duration = endtime - starttime; system.out.println("linkedhashset: " + duration); } from the output below, we can clearly wee that hashset is the fastest one. hashset: 2244768 treeset: 3549314 linkedhashset: 2263320 if you enjoyed this article and want to learn more about java collections, check out this collection of tutorials and articles on all things java collections.
March 29, 2013
by Ryan Wang
· 181,584 Views · 3 Likes
article thumbnail
Introduction to Functional Interfaces – A Concept Recreated in Java 8
Any Java developer around the world would have used at least one of the following interfaces: java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator, java.util.concurrent.Callable. There is some common feature among the stated interfaces and that feature is they have only one method declared in their interface definition. There are lot more such interfaces in JDK and also lot more created by java developers. These interfaces are also called Single Abstract Method interfaces (SAM Interfaces). And a popular way in which these are used is by creating Anonymous Inner classes using these interfaces, something like: public class AnonymousInnerClassTest { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println("A thread created and running ..."); } }).start(); } } With Java 8 the same concept of SAM interfaces is recreated and are called Functional interfaces. These can be represented using Lambda expressions, Method reference and constructor references(I will cover these two topics in the upcoming blog posts). There’s an annotation introduced- @FunctionalInterface which can be used for compiler level errors when the interface you have annotated is not a valid Functional Interface. Lets try to have a look at a simple functional interface with only one abstract method: @FunctionalInterface public interface SimpleFuncInterface { public void doWork(); } The interface can also declare the abstract methods from the java.lang.Object class, but still the interface can be called as a Functional Interface: @FunctionalInterface public interface SimpleFuncInterface { public void doWork(); public String toString(); public boolean equals(Object o); } Once you add another abstract method to the interface then the compiler/IDE will flag it as an error as shown in the screenshot below: Interface can extend another interface and in case the Interface it is extending in functional and it doesn’t declare any new abstract methods then the new interface is also functional. But an interface can have one abstract method and any number of default methods and the interface would still be called an functional interface. To get an idea of default methods please read here. @FunctionalInterface public interface ComplexFunctionalInterface extends SimpleFuncInterface { default public void doSomeWork(){ System.out.println("Doing some work in interface impl..."); } default public void doSomeOtherWork(){ System.out.println("Doing some other work in interface impl..."); } } The above interface is still a valid functional interface. Now lets see how we can use the lambda expression as against anonymous inner class for implementing functional interfaces: /* * Implementing the interface by creating an * anonymous inner class versus using * lambda expression. */ public class SimpleFunInterfaceTest { public static void main(String[] args) { carryOutWork(new SimpleFuncInterface() { @Override public void doWork() { System.out.println("Do work in SimpleFun impl..."); } }); carryOutWork(() -> System.out.println("Do work in lambda exp impl...")); } public static void carryOutWork(SimpleFuncInterface sfi){ sfi.doWork(); } } And the output would be … Do work in SimpleFun impl... Do work in lambda exp impl... In case you are using an IDE which supports the Java Lambda expression syntax(Netbeans 8 Nightly builds) then it provides an hint when you use an anonymous inner class as used above This was a brief introduction to the concept of functional interfaces in java 8 and also how they can be implemented using Lambda expressions.
March 29, 2013
by Mohamed Sanaulla
· 213,278 Views · 18 Likes
  • Previous
  • ...
  • 541
  • 542
  • 543
  • 544
  • 545
  • 546
  • 547
  • 548
  • 549
  • 550
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×