Showing posts with label JDK7. Show all posts
Showing posts with label JDK7. Show all posts

Friday, December 26, 2014

ExecutorService Conundrum

I was asked by someone to solve a problem with threads that they were having. They wanted to cancel a Future that was sent to an ExecutorService. I told them to look at a previous posts I had done on the subject. However, they insisted that this was different. So I took a look at the code. Alas, it was slightly different, but like most folks including me, they were too close to the problem to see the answer. I looked at it, and at first glance I thought something was askew, but it was not.

The code for this project can be downloaded here: runnable-example
As you can see from the results of the run, the future is canceled, but still keeps running. Then it gets interrupted, and breaks. So the question is why is it still running after being canceled.

Here is the Runnable and the main class to execute it:

MyRunnable.java


Main.java


So the do you have an answer? The answer is at the bottom of the blog. Don't peek... think!

Reference

Answer

Simply because you have canceled it, and even interrupted it; it is still a running thread. It is not scheduled, so you are not canceling it before execution.

Thursday, October 09, 2014

How do I check if a Class is an instanceof another Class without initializing it?

Illustration: Cathy Wilcox
We had a recent security audit and a question was posed about how to check a Class without doing an instanceof. This turned out to be a great learning experience. There were a couple of issues that needed to be resolved, first we were loading a Class by passing in its name using something similar to the line below: This will load the Class, but from here how do we check that it is an instanceof without instantiating it?
This can be solved by using isAssignableFrom(Class clazz) as shown below. In this case we are checking if SolientGreen is Green. Some of you will find the moral paradox of being "Green" with Soilent Green.
The second issue is a more potential security problem. How do we load the Class without initializing it. If the Class has a static initializer, the code is executed when the class is loaded. Alas, this is handled by using a variation of Class.forName(String name, boolean initialize, ClassLoader loader) which takes a boolean to determine if the class should be initialized, and a ClassLoader if you want to specify a specific loader.

Finally, we can check the Class like this: When this is run, you will not see the message. Very nice indeed!

So here is the remaining code for education and entertainment:
The code for the project can be downloaded from Bitbucket here: assignable

Thursday, July 10, 2014

cat: How do I list the contents of a text file?

I was asked by a new developer how you would cat the contents of a file in Java. I thought for a second and here is what I came up with. I thought I would just share it. Note: This is my 30s answer, and probably could be cleaned up.

Cat.java


Thursday, January 16, 2014

How do you cancel a scheduled Thread in an ExecutorService?

Executors in the Middle Ages
Humm... I thought...

I was asked this question a while ago, and I came up with a quick solution since it was just a general question. I went back and cleaned up my example which uses Callable and Future to demonstrate the concurrency libraries in Java.

In the example, I use a ExecutorService with a fixed thread pool size of two (2), to make the code slower to demonstrate the point. You can manipulate the value to see the effect on the code execution.

The code is to demonstrate you can do it,  there may be other cleaner ways of doing this. If you have an example, or idea on how to do it cleaner, please comment. :-)

Solution

The code for the project was developed using NetBeans and can be downloaded from Bitbucket at the link below. It is a NetBeans (Apache Ant) based project and should work with Ant without NetBeans.

CallOrderCancel

CallOrderCancel.java


Friday, November 22, 2013

ServiceLoader<S> Dynamic Reloading on JEE7 Web Application

Introduction

We had a technical discussion about updating an application on the fly in Java EE. There were a couple of issues that we were trying to resolve. One was a simple way to add functionality to a web application while deployed, and update the running application. It could be functionality like a new module, or service, or something like, the classic example for the ServiceLoader, codecs.

Additionally, we needed to be able to add the functionality without adding another framework to make it happen. It needed to be something that was available in the existing Java SE/EE APIs. Again, the ServiceLoader seemed to be a possible solution.

I did a Proof of Concept (POC) for using a ServiceLoader to accomplish adding additional services to our application. That worked, but required a restart of the server, or a reload of the application at a minimum. This assumes that the application was NOT auto-deployed. It turns out that worked, but really was only a half-measure. I wanted to see if I could solve the dynamic reloading part, and I did.

Solution

Before we see the code, how does it work in general. We use the ServiceLoader which is part of the Service Provider Interface (SPI) functionality of Java. It is a hidden gem for those who need it, and framework creators can take advantage of this simple, easy to use technology. The ServiceLoader is managed by a Singleton that returns an instance of the ServiceLoader that will return our SPI implementations. In my example, I create an interface that is packaged separately in its own jar and is shared between the deployed web application and the service implementations. The ServiceLoader loads this interface and makes the implementations available. The cool part is that our Singleton class also has some cool NIO and NIO.2 help with the ZipFileSystemProvider to load the implementations from newly added jars. It also has some demo of how to use a URLClassLoader to add our new implementations and update the ServiceLoader.

The code for the project can be found here:

Log.java

Here is our interface that is common between the web service and the SPI implementations.


LogImpl.java

This simple interface will allow me to demonstrate the power of the SPI. Here is an implementation of the API.


LogService

This class is the magic behind the SPI and allows us to dyanmically reload the new implementations as we add them to the WEB-INF/lib directory.


com.bluelotussoftware.service.spi.Log

The SPI file located in the META-INF/services directory of your jar file. This is one version, but each implementation would have its own. The file name is the same as the interface, and the listings on each line are concrete implementations.


IndexBean.java

This bean has a cool NIO method of handling uploaded files. So I thought I would add it. Combined with PrimeFaces, it is functional and pretty.

Conclusion

If you need to add some additional functionality to a web application, and reload it on the fly, Give the ServiceLoader a try. You might just be impressed.

Monday, April 01, 2013

Determining What Classes are Loaded by ClassLoaders

I saw a question posted a couple of months ago on stackoverflow, or a forum. I can't remember where I saw it actually. The question was how do I determine what classes are currently loaded by the ClassLoader when an application is loaded and running. A number of folks posted various solutions like using java -verbose which are of limited help. Another solution was to get using something like ClassLoader.getSystemClassLoader();. The latter looks very promising, but is wrong. I knew that there are a number of classes that are loaded that this would not display.

Ssssh... I will show you how I know.

The problem and solution is surprisingly non-trivial. I thought I would come up with a solution like the one above in 5 minutes. I did come up with one above in about that much time. It turns out to be incorrect.

The solution is to use a Java agent to instrument the JVM and see what it is loading. I am sure a number of you have seen the -javaagent:[=] flag for the VM and wondered what is that for. I am going to show you.

First some results:

all length -> 815
system length -> 163
appLoader length -> 163
classes size -> 61

The first value all indicates all of the classes loaded by the JVM. That is a lot of classes. This is via an Instrumentation agent.

The second value system indicates all of the classes loaded by the System ClassLoader. This is significantly less than loaded by the JVM. This is via an Instrumentation agent.

The third value is the appLoader which is the application classloader. It matches the System, but this may not always be the case. This is via an Instrumentation agent.

Finally, the last value classes is what you get from the ClassLoader without instrumentation. It is a paltry amount of the total classes loaded.

So which one is right? Good question... Here is an answer only a parent, or teacher can give. "It depends."

If I am looking at everything being loaded to check for something forensically I would use the 815 and look at what these classes are and where they came from. If I am checking which classes are loaded to help with reflection, I would look at the 61.

If you have read this far, then you want the code to look at. I have split it into a couple of NetBeans Maven projects hosted on BitBucket using Mercurial.


Code

InstrumentationAgent.java


AgentLoader.java


App.java


Note: I had to put the tools.jar in my Maven repository to make it easy to add as a library.

References

We can not achieve success alone. It is on the shoulders of giants that we see further. I used an example from Dhruba Bandopadhyay to figure out some of the instrumentation process.

Monday, January 14, 2013

GlassFish 3 Tip of the Day: Using JDK 7 with JSP Code

A question came up on the NetBeans J2EE Mailing List about using JDK 7 with GlassFish 3.1.2. Specifically, they were getting the error:
org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP
PWC6197: An error occurred at line: 4 in the jsp file: /index.jspPWC6199: Generated servlet error:strings in switch are not supported in -source 1.5  (use -source 7 or higher to enable strings in switch)

The fix is quite simple. You must include a glassfish-web.xml file in your project, and set a couple of properties. compilerSourceVM and compilerTargetVM.

Please see the example below for a complete configuration.
The project will now compile and use JDK7.

Saturday, January 05, 2013

Java Tip of the Day: Converting an InputStream to a BufferedImage

I was looking for a standard way using the JDK to convert an InputStream into a BufferedImage as part of a JUnit test. The solution was quite simple using ImageIO.

Code

Tuesday, November 13, 2012

JDK7 vs. JDK 6 File Monitoring

One of the really nice advancements, or features of Java 7 is the WatchService. This feature takes advantage of the OS file event notification facilities where available, or otherwise uses a "primitive" polling mechanism. In my blog article WatchService Using ScheduledExecutorService Example, I show an example of how to use the WatchService along with an ExecutorService to do file monitoring. This is really easy to implement and use.

However, the question of how to do it on JDK 6 was posed to me for those who can't do an upgrade for business reasons. I did a quick Google search to see what was out there. Alas, some of the most popular search results were poor, or really badly implemented solutions. I did come across a nice piece of code done by Pascal Essiembre. I didn't find much more on the developer. I would give a link to his work if I were sure that what I found was him. Pascal wrote the code below which is EPL 1.0 so you are free to use it. I used it to check it out, and it works likely in the same manner as the "primitive" implementation in JDK7. Here is the code unmodified from the form I found. This is very nicely done. Good code lives on. I just wish this were more near the top of the search results.

Thanks Pascal for your code contribution to the Java community.

Friday, September 21, 2012

Java Certification Boot Camp - Generics and Collections

Module 04 - Generics and Collections

Java Certification Boot Camp - Object Oriented Design Principles

Module 03 - Object-Oriented Design Principles

Thursday, August 30, 2012

Java Certification Boot Camp - Advanced Class Design - Module 02

This is the second presentation for Java Certification Boot Camp to Java.net and to Scribd for anyone who is interested in the presentation. Module 02 - Advanced Class Design

Java Certification Boot Camp - Java Class Design - Module 01

I uploaded my first presentation for Java Certification Boot Camp to Java.net and to Scribd for anyone who is interested in the presentation. Module 01 - Java Class Design

Thursday, July 05, 2012

Exporting Trusted Certificates in Java

I was trying to export some trusted certificates in Java, and I discovered that the default Java keytool will not do it much to my dismay. So I decided to write a little utility class to export the certificates into PEM files from X509 certificates so it would be easier to move them around.

I thought I would clean up my little tool, and share it with the world.

It requires the GlassFish webservices-osgi.jar which is located in the glassfish-3.1.2/glassfish/modules/ directory along with Apache commons-cli-1.2 and commons-io-2.1.

The application takes a couple of command line arguments to work. It has usages, but the project properties also shows all of them in action. You will need to set that up to match your environment in the IDE. Here is an example.

java -jar certificate-manager.jar -f /Applications/NetBeans/jboss-5.0.1.GA/server/default/conf/server.keystore -i "CN=John Yeary, OU=Development, O=Blue Lotus Software, L=Greenville, ST=South Carolina, C=US" -s 4f2ac2cf -p changeit -e

-----BEGIN CERTIFICATE-----
MIICgTCCAeqgAwIBAgIETyrCzzANBgkqhkiG9w0BAQUFADCBhDELMAkGA1UEBhMCVVMxFzAVBgNV
BAgTDlNvdXRoIENhcm9saW5hMRMwEQYDVQQHEwpHcmVlbnZpbGxlMRwwGgYDVQQKExNCbHVlIExv
dHVzIFNvZnR3YXJlMRQwEgYDVQQLEwtEZXZlbG9wbWVudDETMBEGA1UEAxMKSm9obiBZZWFyeTAe
Fw0xMjAyMDIxNzA3MjdaFw0xMjA1MDIxNzA3MjdaMIGEMQswCQYDVQQGEwJVUzEXMBUGA1UECBMO
U291dGggQ2Fyb2xpbmExEzARBgNVBAcTCkdyZWVudmlsbGUxHDAaBgNVBAoTE0JsdWUgTG90dXMg
U29mdHdhcmUxFDASBgNVBAsTC0RldmVsb3BtZW50MRMwEQYDVQQDEwpKb2huIFllYXJ5MIGfMA0G
CSqGSIb3DQEBAQUAA4GNADCBiQKBgQCa564RyVtq+i+L+BsA0YzmpY4WMkfEn++3s10AbUv/IidT
25TixYqc7ghOkA5HI0z893Gy/ozzB6sGJ6gk8W28VjlU0Y4r0NUhUALuDYnkReWeUiUp4ubPoj/G
71WWu8FFQul+DJWAL7c/963rui812HofQuEWnyZjenrXQMvAUwIDAQABMA0GCSqGSIb3DQEBBQUA
A4GBAECXGuLB/ZB33nGauRsW4kqjiPwpkUoc8N7h44JBVATGx210HzNufixYSqq+AQhW86X2DYJ0
yyBGawVQvpUWoBHCVmmNmu6XdYDfSaCUsPeEt0RoFezruTMz6kaedRwK4zP3H3gp6fHYyiq/mD2M
jTna0zCi4o25E3eiOGKvGBd9
-----END CERTIFICATE-----

The project was developed with NetBeans and GlassFish 3.1.2.

The NetBeans project files can be downloaded here: certificate-manager.zip

TrustedCertificatePEMExportUtility.java


Sunday, February 26, 2012

OpenJDK 7 on Apple G5 PowerPC on Mac OS X 10.5.8

Apple G5 Power Mac

  • Are you an Apple G5 owner feeling a little left out by Apple?
  • Do you have a very expensive and capable piece of hardware which can still be a valuable and fashionable?
  • Do you develop applications in Java, or run applications based on Java and feel left behind?

I have a solution for you! Use OpenJDK BSD Port!

Using a build script sent to me by Kurt Miller, build recommendations from Kelly O'Hair, and the great work of the BSD Port team... I created a new build of OpenJDK 7 for my PPC based system using the Zero VM.

The results are fantastic. I can run GlassFish 3.1.1 along with all my enterprise applications.

GlassFish 3.1.1 on Zero VM
Well it wouldn't be me if I didn't share my good fortune. I updated the Darwin9Build page for OpenJDK to demonstrate how to build OpenJDK for yourself. There are also links to the binaries too.

Here is the link: Darwin9Build


Wednesday, February 08, 2012

Book Review: Murach's Java Programming 4th Ed.

I recently had the pleasure to read and examine Murach's Java Programming 4th Ed. Joel Murach does a good job of producing training and reference manuals for a variety of Java technologies. This is no exception.

The book focuses on Java 7 Standard Edition, but does include a number of other features which were added in Java 5 and Java 6 for completeness.

One of the things I really like is that it uses NetBeans as the IDE to teach Java to the next generation of programmers. A lot of books on Java focus on the language itself. This would have the appearance that an IDE plays no role in learning Java. Any professional programmer will tell you that an IDE is absolutely essential in making you more productive. Joel's choice of NetBeans as a tool to teach Java with demonstrates its ease of use with beginners. Chapter 1 is dedicated to getting the new programmer up to speed with NetBeans.

The book offers educators and trainers optional support materials for teaching. This thoughtful approach to education is vital for anyone teaching Java.

The layout and examples are designed to get the programmer up to speed on the topic being covered.  A typical example of the layout is to have textual material on the left-side page with examples on the right. This allows you to read the material, and refer to the actual code examples. The book layout makes it easy to teach and learn. You are not left reading a volume of material without any code examples to make the essential points. This is a real benefit to the reader.

In addition, the book is developed with exercises to get the beginner involved. The exercises are based on the material learned in the chapter. The example exercises follow a common theme throughout the book allowing you to build on top of the information learned in the previous chapters. This common thread keeps you engaged through the book to see how the different topics tie the applications together.

Overall I would highly recommend the book to anyone looking to learn Java 7, or update their skills. I would give it (4/5) stars.

Chapters

Chapter 3 has a great section on using BigDecimal and arbitrary precision arithmetic. I really liked the explanation and examples. Although BigDecimal was added in 1.4.2 it is not used as much as it should, and this gives it a little press.

Chapter 5 mentions a best practice which is often overlooked. The practice is to add any custom exceptions to the package in which classes are likely to throw them. Often I find that the exceptions are in a package.exception package. This may be a good design if there is a general hierarchy for using the exceptions in multiple sub-packages, but generally is not the case.

Chapter 7 describes a relationship between a class and its instance. The description is eloquent and worth repeating.
"Once an instance of a class is created, it has an identity (a unique address) and a state (the values that it holds). Although an object's state may change throughout a program, its identity never does."
This is a beautiful explanation of OO programming relationships between a class and instance.

Chapter 8 has a discussion on the use of final. The point to be made is that if you declare a class final, all of its methods automatically become final implicitly.

Chapter 10 on nested classes really does a good job of explaining the requirements and limitations of nested classes. There are a couple of exam type gems like an inner class can not contain any static methods, or variables, and a static class can only reside inside another class.

In chapter 11, there was a remark about using Arrays.sort(Object[]) to sort an array. It mentioned that the objects must implement the Comparable interface. I thought that it would "naturally order" without it. I was wrong. I validated that specific case. Even an old dog can learn new tricks.

Chapter 19 is the best tutorial on StAX I have seen. It is simple and easy to follow. After reading the chapter, I will go back and look at StAX when I need this kind of low level XML handling.

Chapter 20 covers Apache Derby (JavaDB). It does a good job of explaining the basics, and gives some implementation recommendations. My only gripe is that the author fell into the Oracle trap of claiming that it is not an enterprise capable database. This is simply not true as borne out from my own experience.

If there is a weakness in the book, it has to do with Chapter 22 on Threads. The chapter does not cover this important topic in enough details. It also does not mention the Java Concurrency Library which has been standard since JDK 6, and handles a lot of the issues with direct thread programming. This chapter should be updated.

Errata

Figure 2-5 Statements that mix int and double variables. The first example requires a cast to int.
int result9 = (int) invoiceTotal / invoiceCount;
Figure 9-1 Example 1 should reflect the current Java design principles. All methods of a public interface are public and abstract.
public interface Printable {
void print();
}
Figure 9-1 Description bullet #3 should read
A classs that implements an interface must provide an implementation for each method defined by the interface, or the class must be declared abstract.
Figure 10-8 Bullet #2 is incorrect. A nested class does not need to be enclosed in a public class of the same file name as the public class. For example X.java could contain the following code:
class P {

    Q q;

    P() {
        q = new Q();
    }

    public Q getQ() {
        return q;
    }

    class Q {

        void print() {
            System.out.println("I am inside P");
        }
    }
}

This will work without being in a public class.

Figure 12-2 Common Collection Classes.
The statement that a HashSet requires that classes to implement a hashcode is incorrect.

Chapter 12 (Page 384) 2nd Para. incorrectly states the two queue methods as push and pull. The pull method does not exist, and was likely supposed to be pop. There are actually three from the Queue<E> interface of note: offer(E e), peek(), and poll.

Saturday, January 21, 2012

NetBeans 7.1 IDE: Remote Database Connections

The NetBeans 7.1 IDE has a feature that has been around for a while, but does not get as much attention as it should. NetBeans allows you to take advantage of using remote databases for doing Java development. There are a number of wizards which can take advantage of connections created in the Services → Database tab.

In the demonstration video, I connect to a remote Apache Derby Database, but the same principals apply to any database as long as you have JDBC drivers available.

Tips & Tricks


To verify that a remote database is Apache Derby (Java DB) which is listening on port 1527 (default Derby port). I connect to the remote application and append XXX;create=true; to the end of the connection string. When I test the database connection, if it is Apache Derby, it will create the new database which confirms our suspicion.

This 3 minute video demonstrates this valuable feature which developers should use for all their database needs.

NetBeans 7.1 IDE: Shelve and Un-Shelve Changes

The NetBeans 7.1 IDE introduces a really cool new feature called shelving. This allows a developer to make changes to a project without committing them to a source control system.

How often have you wanted to try out some new idea on your code without having to check it into source control? This allows you to do just that.

What is shelving?

Shelving creates a patch based on whether an individual file, files, or project is selected. This is a standard patch file and can be applied from the command line, or sent via email to others.

A nice feature is that you can provide meaningful names to the shelved changes. This makes it easier to go back later and apply them to your project.

Note: This functionality is only available for Subversion and Mercurial based projects.

I created a five minute video to demonstrate this really cool new feature.

NetBeans 7.1 IDE: Inspect and Transform to JDK 7

I gave a talk this month at the Greenville Java Users Group (GreenJUG) on the new features, and tips & tricks in the new NetBeans 7.1 IDE.

One of the most popular demonstrations was using NetBeans to download Apache Commons IO from the Apache Subversion repository, open the Apache Maven project natively, and upgrade it from JDK 5 to JDK 7.

This is a real world demonstration of the incredible and powerful new capabilities in the IDE. What is particularly interesting is that the Apache Commons IO project does a great job of providing  unit tests to validate our changes.

I created a 20 minute video which demonstrates this really vital new functionality to help you migrate your projects to JDK 7.

Wednesday, January 04, 2012

OpenJDK 1.7 with NetBeans 7.1 RC on Mac OS X 10.7

A question was posed to me the other day on how to use OpenJDK 1.7 on NetBeans on a Mac since there is only a Developer Preview available. I decided that a video does a better explanation. This applies to NetBeans 6+ as well when using JDK 7 on a default platform of JDK 6.



Popular Posts