This article is more involved with integrating java objects with existing frameworks than the structure/usage of an immutable class.
To use an immutable object with hibernate; the access-type must be configured to use fields. The default access type can vary upon usage. When a class file is mapped via XML, the access type is set to properties (values are retrieved and saved via the getters and setters). Under this condition set the default-access property [under the “default-mapping” tag] to “field.” If hibernate is configured to use annotations, make sure the @id annotation is positioned above one of the fields. With hibernate configured to used fields, the values will be inserted directly into the actual values. Note: Since the class is immutable, an update will never be needed for the class. The only possible operations that can preform with an immutable object are saving [insert], querying, and deleting.
JAXB is a recently included XML serialization library, it is often found in libraries dealing with web services. Its purpose is to convert an object into an XML based representation. It operates in a similar fashion as Hibernate, and requires a similar configuration. To force JAXB to use the instance members, rather than the setters, use the annotation “XmlAccessorType” above the class, and set the value to XmlAccessType.Field. Additionally, it requires a default [zero argument constructor], however that may (and should) be marked private.
Making immutable classes serializable is not as easy as it is with mutable classes. With mutable classes, implementing the Serializable interface [which has no required methods] is all that is needed. With an immutable class, this is not an option. One option to make the class serializable is to have the class implement externalizable. With the externalizable interface the developer must implement and manage the serialization functions. The second option is to create a serialization proxy, within the immutable’s class. How to create an serialization proxy is beyond the scope of this article.
New Java developers may have gotten to this point in the article and started to pull their hair out. They’re asking “How would you create the object if there isn’t a constructor, and how would you define the fields if you restrict them?” Well the best way to define an immutable object is to use an Builder class, that is defined as an inner class to the object.
A builder is a class whose entire responsibility is to build one class. Typically, this is the responsibility of a constructor. However, there are situations where a constructor is not available, as with this, or multiple constructors may decrease a source file’s readability.
Without application, immutable classes serve a very limited purpose. The next few sections will explain how to use immutable objects with various other frameworks/libraries. A beginner may immediately jump to suggest adding the keyword final will solve the problem with immutability. This is incorrect, and depending on where the keyword is, incorrect.
If the final keyword is appended to the class declaration, the class may not be extended. If the keyword is on an instance variable the reference may not be changed after once being declared. If the instance variable is a primitive data type, then the value cannot be changed after the object is constructed. However, if the type is an object, then the content within the reference may be modified [if the object allows mutable access]. If the final keyword is before the return type of a method, the method cannot be overridden by an extending class. If the final keyword is before a parameter, means that the reference may not be changed within the method.
For example, a class that exposes the reference to a Date field of the class may be modified outside of the class by using the reference’s setters. The date object’s main storage of data is based on a long variable. To prevent this from causing an issue in your custom types, non-primitive accessor methods should clone the reference before returning.
An example of this can be seen here:
Main Method:
public static void main(String[] args) {
ImmutableClassicl = new ImmutableClass();
MutableClass mcl = new MutableClass();
Date immutableVar = icl.getToday();
Date mutableVar = mcl.getToday();
//Lets do something destructive
immutableVar.setTime(0);
mutableVar.setTime(0);
DateFormatdform = new SimpleDateFormat();
System.out.println(“The Immutable Class returns: “+ dform.format(icl.getToday()));
System.out.println(“The Mutable Class returns: “+ dform.format(mcl.getToday()));
}
The MutableClass:
public class MutableClass {
private Date today = new Date();
public Date getToday() {
return today;
}
}
The ImmutableClass:
public class ImmutableClass {
private Date today = new Date();
public Date getToday() {
return new Date(today.getTime());
}
}
Please note, there are no modifiers provided in both of the Immutable/Mutable classes. Without modifier methods, the developer should assume that the internal state is not accessible to be modified from the outside world. However, as one would expect this behaves a bit differently. The result of the main method is:
The Immutable Class returns: 10/9/11 9:07 PM
The Mutable Class returns: 12/31/69 7:00 PM
This is a three part series that takes an indepth look at the who, whats, hows, whens, and whys of using Immutable classes. This article assumes that the author can read/understand/use Java, and has some experience with object oriented development, and maybe design patterns.
As their name describes, Immutable objects are objects that cannot be changed after creation. Once the object is created the internal properties of the object are resistant to modification.Typically the signature of an immutable object is: lack of setter methods, private constructors, the avoidance of shallow copies, and preference of deep copies during the creation or in the accessor methods (more about this later).
Immutable objects, when coming from a “Java Bean” perspective, seems a tad frustrating. With Java beans one can easily modify a bean when needed and pass the result to another component. However with immutable objects, this is not possible. To modify an immutable object, after creation, a copy constructor, or a new object has to be created. This now creates 2 instances of similar, but not entirely equal, objects in memory. The creation of a new object takes up more memory for this new instance. If an object is guaranteed not to have been modified, or modifiable then you, the developer, can trust the data within the object not to be changed while you are using it. The primary benefit of this aspect is extremely useful for concurrency [threading]. Now, that you have an immutable object, there is no longer a need to lock the object just to read its value.
Immutable objects don’t solve a very visible problem. They won’t make your program perform new operations. The concept is more of a way of alleviating problems that are potentially in the code already, can enhance readability, provide more security and increase performance. Since the object is assumed to be unchanged, code used to check for modifications [typically referred to dirty bits] is not needed. Additionally lock mechanisms would be eliminated [for reading the object, and technically writing to the object (since that’s not possible with an immutable object)].
Immutable objects are inheritantly more secure; objects are guaranteed to be unmodified. With a modifiable object changes to the object must be validated when they are changed, and after the object has been changed, as opposed to immutable objects [where validation really only occurs at the creation]. Additionally, they are more secure because the creation of the object is the responsibility of another component, how this works will be discussed later.
Immutable objects can become performance enhancement. Since they do not change, the individual instances of the objects can be reused amongst different threads, processes [potentially], and applications without concern of modification of the program’s operation. Additionally with removing the need for locking surrounding the immutable object you can get rid of potential deadlocks and locking overhead. However, with the creation of new objects, one must be aware about the total amount of objects, and memory being allocated. Large amounts of allocations may provoke garbage collection, or worse, cause the application to run out of memory.
With exceptions to extreme cases, worrying about the memory usage [compared to using modifiable instances] is more of a sign of a premature optimization, than a reasonable concern. Some of the extreme cases are: very small embedded systems [where available in KBs rather than MB/GBs], or prevalence in your application. If immutable objects are used for the sake of being used, then the benefit of the immutable objects are negated. A few examples include: short life of the objects [the objects are being used only in a short scope and were never written to anyways], needless copying of similar immutable objects (but with a different instance). These abuses of the immutable object pattern can be corrected by using a flyweight pattern, and expiration, to create, cache, and prune the objects. The issue with small systems requires more thought, testing, benchmarking, and prior design before considering immutable objects.
One of the best benefits of immutable objects is that the creation of the object can be managed, and restricted. The creation of the immutable objects can be restricted to factory methods [within a flywheel]. This means that a caching model can distribute previously created objects, and create new requested objects on demand. By using the factory method and fly weight patterns, memory can be efficiently managed and objects can be better managed. Additionally, if the caching module usages WeakReferences, and there are not other usages of the object, then the unused objects would become a higher priority for the garbage collector to collect.
Additionally by introducing hashing, and reusing objects, you are able to get the benefit of having less object allocations in the VM. This, in turns, reduces the probability of the GC running, and needless objects from being created.
Reporting is, generally, one of the most boring tasks/subsections of Software Developments. The level of “uninterestingness” is exemplified by the “TPS” reports in OfficeSpace. However, reports can be awesome. They can be incredibly useful when they help you if they accomplish your tasks, are interactive, and show data in a convenient/uncluttered fashion.
Unit testing is one of the categories that is absolutely necessary in development [even more so for larger systems], however the tools to scour these tests are often unhelpful. The tools that interact with NUnit, JUnit, GUnit tend to just reveal the results of the tests shown. Code coverage tools help, in reporting back the % of code covereed by the tests [and some times, with TestCacoon (C++), and EMMA/EMMA-compatable (Java) IDEs] However these tools lack an overall reporting capiblity to say “hey these bits/seconds/methods/components” lack the coverage the most in your code.
The only tool that I have found so far that will handle this is Clover [by Atlassian]. The features look great. Unfortunately, the product requires having a centralized build server. Which is a little too much to ask for hobby projects. [Speculation warning] To use this, it would require a continuous integration/build server setup. Also, the cost maybe little high [$1200 for a 1 machine server] to make an off the cuff suggestion to management.I realize the return for a product may exceed the cost of developing a huge commercial product, however it is a little difficult to determine that [without the evaluation trial (if requires an build server and you don't have one that's a lot to ask for an evaluation)]. They do have an desktop version, but from the screenshots and the description, I wonder how well that would work [being a web client]. Also, I doubt that it includes C++/GUnit support.
If you are having issues with bundling JasperReports, a J2EE server, and Maven, you are not alone. There are many bumps in the road for getting JasperReports integrated with Tomcat/J2EE Container and building with Maven. Hopefully, this blog entry will make things slightly easier.
Firstly, there is the confusion of where the JasperReports dependency lies in the maven2 repository. There is a very suggestive entry for: {groupid: jasperreports, artifactid: jasperreports} however, that entry only hosts versions 0.5.0 to 3.5.3. The entry: {groupid: net.sf.jasperreports, artifactid: jasperreports} contains the versions 3.6 to the latest version. In addition, the last entry contains an artifactid of jasperreports-fonts, handy if special reporting fonts are requested from your reports.
Secondly, if you are getting ClassNotFoundException or NoClassDefFoundError for the class: net/sf/jasperreports/engine/JRException your issue with still with the POM configuration for JasperReports. The ClassNotFoundException is a runtime error, so despite a successful build, you will still see this. Despite the jasperreports-x.x.x.jar file being in your web-inf folder, you may still see this error.
You must modify the scope of the component in the pom.xml. Change the scope from compile [which is needed to build], to “provided.” (http://maven.apache.org/pom.html#Dependencies) Provided not only uses the dependency to build, but update’s the container’s classpath to use this as a runtime dependency.
Keeping to a similar topic as the last few posts, I thought I’d come up with a list of the train stations that I have got on a train at or got off. Passing through, or stopping for a break does not count. [For those overseas: Amtrak stops for cigarette breaks every so often] Secondly, I couldn’t let Warren outdo me with his trainstation list.
Link to the High Speed Rail Meeting in Raleigh 5 April 2011
An update on the High Speed Train’s bill. For those who read this blog, all 0.5 of you, will remember the letter I sent to Rep. Killian about attempts to block funding for high speed rail. I just thought I would post an update on proceedings in regards to this. The link included shows some of the debate going on. I was quite amused when Rep. Killian made this astounding claim: “Well of course the mayors are in favor of this, they benefit from it.” The amusing bit of this is that Killian unwittingly acknowledges that this service would be a benefit. Killian’s rhetoric implies that residents of Mecklinburg County would not benefit from this. This is counteracted by Rep Carney of Meckenburg, and Mayor Foxx (who rode to the meeting via Amtrak).
Many people claim that “The World Has Changed” when they see something they don’t recognize from before. This common phrase is a cliché. It is cliché that is used, and abused, without actual regard to gradual change or reflection of major influences. The most irritating resultant of this phrase is that it manages to provide little meaning, and prevents critical rebuttals. It is quite difficult to argue against the context in which this phrase is used. The phrase, however vague and meaningless, is not false, but it is not exactly true. Human civilization evolves, not necessarily in the biological sense, by taking existing ideas and improving on them. There are many who have claimed that they have created something that did not exist before, is that they are severely unaware of similar existing ideas, or of previous attempts.
The world has changed to attempt to bridge the content of one idea to another weakly connected idea. For example one could say: “People used to dig in the ground with stones, but the world has changed. Now people use backhoes [UK/AUS: diggers].” This phrase makes a statement that something that cannot be refuted. The phrase makes a magical leap to another similar connecting statement, similar to “hand waving,” that ignores the connections between the two phrases. The gap between the two phrases is not bounded. The amount of context connecting the two phrases could include wars, world peace, and space exploration. The typical westerner, with agricultural experience, would association the connection of digging with rocks to diggers to be rocks->sharpened rock->shovel->machinery/hydraulics->jackhammer->digger. However, the original intent [or persuasion] may have been to get the listener to open up to the idea of the gap being a magical entity creating the advancement [good for hyping up products and investment in organizations], or a massive leap in the human condition.
Clichés are phrases that are similar to slang, they are the disease of the everyday language. Easy to catch from another, easily spotted, and difficult to get rid of. These clichés are popular amongst cultures, and communicate generic feelings; however they also tend to hide realities. In summary, the phrase attempts to convince the listening party that humanity has drastically changed. Somehow, humanity can no longer satisfy their basic needs without advancements. Somehow, without the TV, humanity can’t feed itself, interact with others, or even reproduce without being directed. Inversely, it also implies that the notion that cultures which do not share the same opinion of the change are backwards and somewhat incompatible is inheritantly wrong.
Lastly, I leave with a visualization of behavior change in the last 10 years. Has the human population changed that much? Yes there have been minor changes in consumption of resources, but has the mobile phone really introduced communication as a new concept to human beings? Have we lost the same desires to interact with each others? No, we’ve been doing it for many years and will continue to do so.
Visualization 2000 vs. 2010 Behavior and Cultural Statistics
Dear Mr. Killian,
I was rather shocked to see your support for House Bill 422. I was expecting to see the support for this bill by those who are in counties not served by Amtrak. The looks of the primary and cosponsors of the bill, you stand out. How does your proposal align with the needs of Charlotte/Mecklenberg county?
I have traveled via Amtrak many times over the last two years. I am not dependent upon it for long travel, mostly due to the low speed. I understand that this upgrade does not stand to provide a great increase in service or noticeable benefit to the user, however it does stand as an needed upgrade to the infrastructure within North Carolina. Additionally there have been reports, by the Association of American Railways, of increased usage of the railways.
Your stand does not seem to conform to the following interests:
1. Your personal interest in occupation [high speed rail is a selling point if there is a terminal in your area, its a way to get to either Atlanta or Washington DC (if you sell it right)]
2. The interests of the people that you represent [Mecklenburg Residents use public transport, if it is well maintained (we have the "Gold Rush Trolley" in addition to the light rail)
3. It does not fit the interest in the creation of jobs or investment in NC infrastructure. Improvements
Unless there is another reason, it appears to me that you are riding on the coat tails of the national party [republicans] rather than representing the people that voted you in. If this is the case, shame on you. Additionally if this is the case, you have motivated me to participate in the next election to campaign for your competitor and vote for them.
The grant is an easy way of getting money for improvements. Where else will you get this kind of benefit without resorting to interest barring municipal bonds?
Technology, since the introduction of a computer that doesn’t take an entire room, has always been suggested for educational purposes. Technology is sold as an existing off the shelf solution for teaching the youth of the country that it happens to be in. Policymakers and lobbyists tend to sell the idea of technology as an easy solution that just takes money to solve a massive problem.
When an education organization purchases a technology solution many things happens. Typically, given a healthy market, products are evaluated, money is appropriated, and the solution providers bid [through their price, and service offerings]. The goal in this market is to provide business for the producer through a bulk sale, and reduces the price for the consumer [the people who run the educational organization]. This is the only place where the ultimate beneficiary, the students, is represented is by the purchaser of the products. However, since price is a consideration in the sale, the people who ultimately use and learn from the product have to compete with price.
Approximately fifteen years ago, the utopian goal of “high class education” was to have popular educational software or to have internet access in the classroom. By putting this in the classroom it was assumed that students would immediately consume it and use it to fulfill academic interests. Well intentioned as this might be, it wasn’t the case. Few students used the internet for research, and for those who did typically did, performed poor research. The research came from poor resources, and nothing was taught about how to identify a creditable source. However, can you blame the ten year old, teaching him about creditable sources isn’t extremely easy to explain when they’re struggling on algebra. Most students in schools used the internet to fulfill their immediate, typically non-education related, interests.
I would argue that most students below the age of mandatory education are unable to determine what subjects are the best investments of their time. Mandatory education provides a basic understanding of our world and the options available. It provides an understanding for the person that options exist outside of their small town or city, and that society is no longer a basic rudimentary system of barters and trades or tradition based.
Recently there has been a lot of hype over the use of embedded systems. This started with the introduction of “learning toys.” Some of these include LeapFrog, and VTech related products. Typically the premise of a learning toy is taking simple concepts, dressing them up in cute and popular characters and making an electronic version, which can be easily purchased at the local toy store. These are an easy way for a child to reinforce what is taught from another source, however, they are not a great teacher.
One of the more recent fads in technology purchases in education is the use of iPods, iPhones, and iPads. Ironically, these are all produced by the same company, which reduces competition in the market. These purchases are typically favorited by those who have a financial interest or for those who deem it hip. These devices are not built for educational use. These devices are all built to be generic multi-use devices for communication, or entertainment. Many argue that these devices can be used educational purposes; however they were not designed to entertain the needs that an educational experience requires.
For example, if an iPad is used for an educational purpose, what stops the user from switching to OMGmyFavoriateCeleb.com or texting their bff Jill when the material becomes dry and uninteresting? If anything, an iPad, in this manner, cuts down on educational value. The cost of the switch in context [going from information to a pleasure seeking mode] eliminates analysis on the material that was uninteresting. Without the device, the user may wonder why he or she did not like the subject or why it may be dull.
Additionally, the issue with selling devices that were mentioned is ignoring the actual value they may have. The value of an iInsertNameHere is completely reliant on the applications that are installed and the use of them. The users of the technology will ultimate install what they want on it. Why install the “utimate visual guide on history” when you can install the latest fart application for only $0.99 (now reduced from $50). The only few applications where I can see a tablet that would be useful for education is for reading material (books) or music (a Finale like application). However, typically the cost of the books, in the format for the tablet, and the device itself would never be less than the cost of the books themselves. Given that the only situation where the statement would be false is for rare books. Given a situation where everyone purposed books as ebooks, that possibility may not be far off.
Now for the content that is less doom and gloom. Technology can enable people to learn. There have been success stories. Two of the best success stories are electronic publishing of scholarly journals, and the second one being the OLPC project. Electronic publishing of scholarly journals, attempts to help the academics field to reduce the publishing of multiple research attempts of the same findings, create new fields of study, and providing access to academic materials to more people than ever before. Electronic journals are typically subscribed to by universities and access is provided to students. Without electronic access, this would become quite expensive at universities with large amounts of students (with a high demand for articles).
The second success story is an odd one. The project is the One Laptop Per Child project. This project’s goal is to put MORE computers in the hands of more children. However the difference in the people who are getting the machines and the ones I was ranting about before, is that these consumers are children in developing nations. The project is not putting laptops are specifically designed for situations where the internet may not be widely available, or electricity may be a concern. Additionally these are designed for locations where educational materials may be rare or outdated. The main characteristic that makes this project successful is that these laptops are not built to be general purpose entertainment devices. These devices are created to limit the applications that the people can use.
When I was the target for these educational devices, also the time of the dinosaurs, there were a few educational games that came to mind. These games were “Mathblasters”, “Where in the world is Carmen Sandiago,” and “Oregon Trail.” These were fun games that weren’t designed to replace the educational experience.