Sunday, May 31, 2009

Java Properties Without Getters and Setters

During the last Devoxx conference, Mark Reinhold, Sun's chief engineer for Java SE, gave a presentation on the latest directions for Java 7. (Hamlet D'Arcy's summary of Mark's presentation is available here.)

One of the features that was discussed for possible inclusion in Java 7, but won't find its way into the final release, is first class properties for Java. First-class support for properties would have gone beyond the simple setter and getter methods of the JavaBeans specification, and provided a succinct and elegant way for defining properties for Java objects.

Properties are already first-class elements of many modern languages, so this lack in Java 7 will be felt by many developers accustomed to other languages' property support. At the same time, Java developers can resort to a handful of other techniques in working with property-like Java attributes, and some of the possible techniques work even in Java 1.4. In the rest of this article, I will demonstrate one such technique use a simple aspect, with AspectJ, and some following some conventions.

Motivation

The idea for this solution arose while working with the OpenXava 3 framework. OpenXava defines a mechanism to develop Java Enterprise applications using Business Components. It's an alternative way to MVC: instead of organizing the code into Model, a View and a Controller, the code with OpenXava is organized around Invoice, Customer, Order, and similar business-centric objects. OpenXava initially used XML for defining components, but since version 3 the use of POJOs with Java 5 annotations also became available as the preferred way to define business components.

When using the XML-based object definition, you may specify a component in the following manner:

<component name="Teacher">

<entity>
<property name="id" type="String" key="true"
size="5" required="true"/>
<property name="name" type="String"
size="40" required="true"/>
<collection name="pupils">
<reference model="Pupil"/>
</collection>
</entity>

</component>

Using the annotation-based OpenXava 3, the same component would be defined as follows:

01.@Entity
02.public class Teacher {
03.
04. @Id @Column(length=5) @Required
05. private String id;
06.
07. @Column(length=40) @Required
08. private String name;
09.
10. @OneToMany(mappedBy="teacher")
11. private Collection pupils;
12.
13. public String getId() {
14. return id;
15. }
16.
17. public void setId(String id) {
18. this.id = id;
19. }
20.
21. public String getName() {
22. return name;
23. }
24.
25. public void setName(String name) {
26. this.name = name;
27. }
28.
29. public Collection getPupils() {
30. return pupils;
31. }
32.
33. public void setPupils(Collection pupils) {
34. this.pupils = pupils;
35. }
36.
37.}

This illustrates some of the verbosity with the Java definition: 37 lines against the 13 of XML version. The problem occurs because of the getters and setters. The boilerplate code adds noise and increases the size of the file without increasing the information to the programmer. Use Java and annotations as a definition language in OpenXava would welcome a more succinct and elegant syntax.

A More Succinct Solution

A better solution can be obtained by defining the business component in this way:

01.@Entity
02.public class Teacher {
03.
04. @Id @Column(length=5) @Required
05. public String id;
06.
07. @Column(length=40) @Required
08. public String name;
09.
10. @OneToMany(mappedBy="teacher")
11. public Collection pupils;
12.
13.}

This makes Java more beautiful, succinct and elegant... just as XML.

With this, you have to use the following properties without getters and setters. That is, instead of:

1.teacher.setName("M. Carmen");
2.String result = teacher.getName();

you write:

1.teacher.name = "M. Carmen";
2.String result = teacher.name;

In this case name is not a field, but a property. You can refine the access to this property, and even create pure calculated properties.

For example, if you wanted a calculated property, you could define it in this way:

01.@Entity
02.public class Person {
03.
04. ...
05.
06. public String name;
07. public String surname;
08.
09.
10. transient public String fullName; // (1)
11. protected String getFullName() { // (2)
12. return name + " " + surname;
13. }
14.}

In order to define a calculated property, you define a public field (1) and then a protected (or private, but not public) getter (2). This getter, getFullName() in this case, is for implementing the logic for the property fullName.

Using this property is simple:

1.Person p = new Person();
2.p.name = "M. Carmen";
3.p.surname = "Gimeno Alabau";
4.assertEquals("M. Carmen Gimeno Alabau", p.fullName);

When p.fullName is used, the method getFullName() is executed for returning the value. You can see that fullName is a property, not a simple field.

You can also refine access to writing and reading the properties. For example, you can define a property as following:

1.public String address;
2.protected String getAddress() {
3. return address.toUpperCase();
4.}

When address is used from outside the class the method getAddress() is used to obtain the result, but this method only returns the address with some refinement. As we use address field from inside getAddress() field address from inside of its class is used, and the getter is not called.

Now you can use this property as follows:

1.Person p = new Person();
2.p.address = "Av. Baron de Carcer";
3.assertEquals("AV. BARON DE CARCER", p.address);

As well, you can define setters, even for vetoing the data to be set, as in the next example:

1.public int age;
2.protected void setAge(int age) {
3. if (age > 200) {
4. throw new IllegalArgumentException("Too old");
5. }
6. this.age = age;
7.}

As in the case of the getter, if a setter method is present it will be executed to set the data, you can use this logic to set the data to the field or for any other logic you want. Now you can use this property in this way:

1.Person p = new Person();
2.p.age = 33;
3.assertEquals(p.age, 33);
4.p.age = 250; // Here an IllegalArgumentException is thrown

In summary:

  • Properties behave from outside of the class as public fields.

  • If no getter or setter for the field exists, a direct access for the field is performed.

  • If a getter exists for the field, it will be executed when trying to read the field from outside.

  • If a setter exists for the field, it will be executed when trying to write the field from outside.

  • From inside the class, all references to the field are direct access, without calling getter or setter.

This provides a simple and natural way to have properties in Java without unnecessary getters and setters.

Implementation

This simple mechanism is easy to implement using AspectJ and a simple aspect, and it will work even in Java 1.4.

For this to work, you only need to have an aspect in your project:

01.aspect PropertyAspect {
02.
03.
04. pointcut getter() :
05. get(public !final !static * *..model*.*.*) &&
06. !get(public !final !static * *..model*.*Key.*) &&
07. !within(PropertyAspect);
08. pointcut setter() :
09. set(public !final !static * *..model*.*.*) &&
10. !set(public !final !static * *..model*.*Key.*) &&
11. !within(PropertyAspect);
12.
13. Object around(Object target, Object source) :
14. target(target) && this(source) && getter() {
15.
16. if (target == source) {
17. return proceed(target, source);
18. }
19. try {
20. String methodName = "get" +
21. Strings.firstUpper(
22. thisJoinPointStaticPart.getSignature().getName());
23. Method method =
24. target.getClass().
25. getDeclaredMethod(methodName, null);
26. method.setAccessible(true);
27. return method.invoke(target, null);
28. }
29. catch (NoSuchMethodException ex) {
30. return proceed(target, source);
31. }
32. catch (InvocationTargetException ex) {
33. Throwable tex = ex.getTargetException();
34. if (tex instanceof RuntimeException) {
35. throw (RuntimeException) tex;
36. }
37. else throw new RuntimeException(
38. XavaResources.getString("getter_failed",
39. thisJoinPointStaticPart.
40. getSignature().getName(),
41. target.getClass()), ex);
42. }
43. catch (Exception ex) {
44. throw new RuntimeException(
45. XavaResources.getString("getter_failed",
46. thisJoinPointStaticPart.getSignature().getName(),
47. target.getClass()), ex);
48. }
49. }
50.
51. void around(Object target, Object source, Object newValue) : target(target) && this(source) && args(newValue) && setter() {
52. if (target == source) {
53. proceed(target, source, newValue);
54. return;
55. }
56. try {
57. String methodName = "set" +
58. Strings.firstUpper(thisJoinPointStaticPart.getSignature().getName());
59. Class fieldType = ((FieldSignature)
60. thisJoinPointStaticPart.getSignature()).getFieldType(
61. Method method =
62. target.getClass().
63. getDeclaredMethod(methodName, new Class[] {fieldType});
64. method.setAccessible(true);
65. method.invoke(target, new Object[] { newValue } );
66. }
67. catch (NoSuchMethodException ex) {
68. proceed(target, source, newValue);
69. }
70. catch (InvocationTargetException ex) {
71. Throwable tex = ex.getTargetException();
72. if (tex instanceof RuntimeException) {
73. throw (RuntimeException) tex;
74. }
75. else throw new RuntimeException(
76. XavaResources.getString("setter_failed",
77. thisJoinPointStaticPart.getSignature().getName(),
78. target.getClass()), ex);
79. }
80. catch (Exception ex) {
81. throw new RuntimeException(
82. XavaResources.getString("setter_failed",
83. thisJoinPointStaticPart.getSignature().getName(),
84. target.getClass()), ex);
85. }
86. }
87.}

Having defined this aspect, you will need to compile your project using AspectJ.

The aspect intercepts all access to public fields in the model package, then use introspection to call to the getter or setter method if they exists.

Drawbacks

Unfortunately, this approach has at least two important drawbacks:

  1. It does not work when you access to the properties using introspection.

  2. With JPA, at least using the Hibernate implementation, lazy initialization does not work.

You may think that the introspection problem can be overcome with your own custom introspection code. But the man third party libraries, frameworks, and toolkits will not obey those rules. For example, if you are using a report generator that can generate a report from a collection of Java objects, the report generator may expect real public getters and setters in the objects.

The JPA the specification for Java Persistence API states that: 2.0:

"Instance variables must not be accessed by clients of the entity. The state of the entity is available to clients only through the entity methods i.e., accessor methods (getter/setter methods) or other business methods."

JSR 317 : JavaTM Persistence API, Version 2.0 - Public Review Draft - Section 2.1

That is, portable JPA code should not rely on direct access to properties.

Conclusion

This article presents a very simple way to work with properties in Java, even though the language doesn't support properties. If the AspectJ implementation is not practical, you can find other implementations of this idea using asm or cglib.

References

OpenXava - http://www.openxava.org/

AspectJ - http://www.eclipse.org/aspectj/


Thanks to the original source and the author

Machine Structures 1: What do you need to build a computer

What do you need to build a computer

– Memory

• To store program instructions

• To store intermediate data values

– Calculator

• To carry out calculations

• Commonly called an “ALU”, which stands for Arithmetic / Logic Unit

– Instruction Set Architecture

• Describes format of program instructions

– One example: SICP RML (not very practical)

– Another example: the “Beta” (more representative of real machines)

– Control Machine

• To interpret the instructions and tell the data memory and ALU what

to do.

What else do we need?

• A PC or Program Counter to keep track of where we are in

the program memory.

• A way of controlling the PC depending on if statements

(conditionals).

• Some method of remembering where we’ve been when

doing recursive calls, because the PC isn’t enough

• Some method of managing memory for subroutine calls,

heap storage, etc ...

High Level to Assembly Conversion

Java Code:

z = x + y;

Instruction:

(assign (reg z) (op +) (reg x) (reg y))

Representation of the Instruction:

Reg Y

Reg X

Reg Z

OP Code







Memory Architecture:





What’s Wrong with this?

• If we have lots of data, the pointers into

data memory can become very Wide

• If the pointers are very Wide, then the

instructions will need to be very Wide.

• Other problems: The nature of memory

systems.

Why Big Data Memories are Slow?

• The more selection a chip needs to do, the longer

it takes to find the data being selected.

• Big memories are off-chip, and communications

within an integrated circuit are fast, communications between chips are slow.

A good idea:

• Invent a small “register file” which most instructions will point to for

data source and destination.

• Invent new Memory-type instructions for

– Loading data from the bigger data memory to the register file

– Storing data to the bigger data memory from the register file

• New ALU-type instruction format

e.g. ADD R0 R1 R2

e.g. LD 43264, R0

LD 932643, R1

ST R2, 43265

Instruction Set Design

• Wide choice in # of addresses specified

– 0 address (stack) machines (e.g. Java virtual machine) – 0 Registers e.g., add [uses stack to get the data]

– 1 address (accumulator) (e.g. 68hc11) – 1 Registers e.g., add r1

– 2 address machines (e.g. Dec PDP-11) – 2 Registers e.g., add r1, r2

– 3 address machines (e.g. Beta) – 3 Registers e.g., add r1, r2, r3

• Wide choice of complexity of instructions

CISC vs. RISC (e.g. I86 vs. Beta)

Note: CISC is Complex Instruction Set Computer and RISC is Reduced Instruction Set Computer. As the name suggests CISC is more complex than RISC and the category of RISC and CISC is based on the number of instructions needed to perform an operation and the time taken to perform an instruction.


Saturday, May 30, 2009

Google WAVE: The Next Gen Collaboration Tool

Yesterday at Google I/O attendees got to see a preview of the new Google Wave communication system. Developed out of the Google Sydney offices, Lars Rasumussen says that Wave is "what email would look like if it were invented today".

The team that developed the application are brothers Lars and Jens Rasmussen and Stephanie Hannon. The Rasmussen brothers are the geniuses behind Google Maps, which was a significant change in the way we look at the web today. I'm happy to see they haven't stopped thinking about innovation since then.

So what is it all about? Wave combines GMail, GTalk, GoogleMaps and Google Docs all together into a truly collaborative, online workspace. The following summary from the creators of the technology describes what it can do nicely:

"In Google Wave you create a wave and add people to it. Everyone on your wave can use richly formatted text, photos, gadgets, and even feeds from other sources on the web. They can insert a reply or edit the wave directly. It's concurrent rich-text editing, where you see on your screen nearly instantly what your fellow collaborators are typing in your wave. That means Google Wave is just as well suited for quick messages as for persistent content -- it allows for both collaboration and communication. You can also use "playback" to rewind the wave to see how it evolved." - Lars Rasmussen

There's also a full Wave API allowing developers to enhance Google Wave. You can build extensions or embed it into your site. Ola Bini has already developed an example of an Ioke Wave Robot. Google also wants to expand ther platform to different providers through the Wave Federation Protocol. Apparently it will be available for all sometime this year.

Google have done a great job of creating a feel-good conference, even during these times, by giving out a free HTC Magic (G2) phone running Android to all attendees. Man, I wish I was there!

The excitement around this announcement does make me wonder why there isn't more interest in the Eclipse Communications Framework project. In ECF you get real time shared editing, instant messaging - real collaboration all within you Eclipse IDE. As always, I encourage you to get involved in projects like this, so we can have innovation in our IDEs as well as in our browsers.

Thursday, May 28, 2009

JAVA: VisualVM - Free and Open Source Java Troubleshooter

The 3rd milestone of VisualVM was released a few days ago. That release marks the open sourcing of this troubleshooting tool, together with the further polishing of its API. Perhaps this is therefore an opportune moment to spend some time exploring its main features. The key to understanding VisualVM is to see it as a bundling of a number of JDK tools, such as JConsole, jstack, and jinfo, combined with several new and advanced profiling capabilities. The tool is designed for both production and development use and further enhances the capabilities of monitoring and performance analysis for the Java SE platform.

All Java applications running on the same system as the VisualVM are listed in the "Applications" tab on the left side of the tool. Java applications on remote systems are also shown, under the "Remote" node. Information specific to each of the applications, which includes VisualVM itself, is displayed in the main part of the tool. For each application, there is an "Overview" tab showing general information, such as process ID and the Java version used to run the application.

The "Monitor" tab shows graphs for the application's heap, permanent generation, threads, and classes. The total heap space is shown in one color and the amount of heap space in use is shown in another. Below, you see the "Threads" tab, shwoing thread visualization for VisualVM itself:

VisualVM can read and interpret binary heap dump files. You can either generate a heap dump from within the VisualVM or you can open one, via the "Profile" menu at the top of the tool. The heapwalker part of the tool can then provide information about the dump, as shown in the next two screenshots:

The heapwalker can help you track down memory leaks. The instances view, shown above, shows all object instances of a class, from where you can find the nearest garbage collection root points.

VisualVM is pluggable. It comes with a Plugin Manager which already contains three plugins:

The VisualVM-MBeans plugin gives you an MBean Browser. It does the same as JConsole's MBeans tab: "The MBeans tab allows you to access the full set of the platform MXBean instrumentation. In addition, you can monitor and manage your application's MBeans using the MBeans tab." It lets you get and set MBean attributes and invoke MBean operations as well as subscribing for MBean notifications. Here's how it looks, once you've installed the plugin:

The Visual GC plugin gives you a graphic overview of information relevant to garbage collection:

Finally, your investment in JConsole plugins is protected, because they can be loaded into the VisualVM, in the same way as how they were loaded into the JConsole. First, you'd need to install "VisualVM-JConsole" plugin that is shown in the 4th pic above. Then, VisualVM is receptive to any JConsole plugin. For example, let's take the JTop plugin. JTop is a JDK demo that shows the thread CPU usage of all threads running in the application. This demo is helpful in identifying the threads that have high CPU consumption. This is how it is installed in the JConsole:

1.<JDK6>/bin/jconsole -pluginpath <JDK6>/demo/management/JTop/JTop.jar

And, to install that same plugin into VisualVM, you simply open the etc/visualvm.conf file and then add the following to the "default_options" setting:

1.-J-Djconsole.plugin.path=<JDK6>/demo/management/JTop/JTop.jar

For JTop, you'd then end up with the following, in a new tab, that is, the JConsole tab, provided by the aforementioned VisualVM-JConsole plugin:

With the release of the 3rd milestone, you can try out the APIs and create your own plugins. When you go to the download page for VisualVM, you'll see a link for the VisualVM binary as well as a Milestone 3 API Docs link. That gives you access to the Javadoc, as well as an overview of the entrypoints to VisualVM. However, note that the API is still in progress and cannot be considered stable yet.


Thanks to the original author and the source

Wednesday, May 27, 2009

Math: Find the digit

Find the Digit

Let N be the largest integer such that N and 7N both have 100 digits.

What is the 50th digit of n?

If N is the largest number such that N and 7N both have 100 digits, then 7N must be the largest multiple of 7 that has 100 digits. We can therefore find N just by dividing 7 into 9999...99 (100 9's).

By simple long division, we find that N starts off with repeated blocks of 142857. The first, seventh, thirteenth, ..., forty-ninth digits must therefore be 1's, and so the fiftieth digit is a 4.

Monday, May 25, 2009

Math: Formula for Squares

Formula for Squares

Show that if x is a postive integer, and both 2x + 1 and 3x + 1 are squares, then x is a multiple of 40.

We work with the modulo classes of 5 and 8. Any square number must leave remainder 0, 1 or 4 when divided by 5 or 8:

n
(mod5)
n2
(mod 5)
00
11
24
34
41
n
(mod8)
n2
(mod 8)
00
11
24
31
40
51
64
71

Now lets examine the remainders when 2x + 1 and 3x + 1 are divided by 5 and 8:

x
(mod5)
2x+1
(mod 5)
3x+1
(mod 5)
011
134
202
320
443
x
(mod8)
2x+1
(mod 8)
3x+1
(mod 8)
011
134
257
372
415
530
653
776

From the table on the left, we see that it is only when x = 0 (mod 5) that both 2x + 1 and 3x + 1 have remainders 0, 1 or 4 mod 5 that allow both of them to be squares. Similarly from the second table, we must have x = 0 (mod 8).

Thus 5 and 8 both divide x, and so x is a multiple of 40.

The first few values of x with both 2x + 1 and 3x + 1 square are x = 0, 40, 3960, 388080, 38027920, 3726348120, ...