Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Monday, April 17, 2017

Implications of the Presence of StringBuffer

When I am working on legacy code and run across instances of StringBuffer, I typically replace them with instances of StringBuilder. Although a performance advantage can be gained from this change, I often change it in places I know will have little noticeable effect in terms of performance. I feel it's worth making the change for a variety of reasons in addition to the potential for performance benefit. There's rarely a reason to not choose StringBuilder over StringBuffer (API expectations are the most common exception) and the existence of StringBuffer in code misleads and provides a bad example to those new to Java.

In the book The Pragmatic Programmer: From Journeyman to Master, Andy Hunt and David Thomas discuss "the importance of fixing the small problems in your code, the 'broken windows'." Jeff Atwood touched on this subject in the post The Broken Window Theory and it has been more recently addressed in the posts Software Rot, Entropy and the Broken Window Theory and Don't leave broken windows. The presence of StringBuffer implies a staleness in the code. In effect, use of StringBuffer may not be a "broken window," but it's a really old, leaky single-pane window that should be replaced with a modern, energy-efficient double-pane window.

I found Peter Lawrey's recent blog post StringBuffer, and how hard it is to get rid of legacy code to be an interesting take on other implications of StringBuffer that still exist in code. Lawrey quotes the last paragraph of the StringBuffer class Javadoc documentation, "As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization." Lawrey then uses simple Java methods and jmap to demonstrate that instances of StringBuffer are still used in classes and libraries delivered with the JDK even as late as Java 8.

Lawrey points out that the presence of StringBuffer in frequently used Java code more than a decade after the introduction of "drop-in replacement" StringBuilder is evidence of how difficult it is to "clean up legacy code." Lawrey's full conclusion states, "Using StringBuffer on startup doesn’t make much difference, but given it has a well known, drop in replacement, and it is still used, even in new functionality more than ten years later shows how hard it can be to clean up legacy code or to change thinking to get people to use best practice libraries."

I decided to try out one of Lawrey's simplest examples when compiled with Java 8 Update 121 and when compiled with a recent release of OpenJDK 9. I (slightly) adapted Lawrey's example to the simple "Main" class listing shown next.

Main.java

import java.io.IOException;

/**
 * (Slightly) adapted class from blog post
 * "StringBuffer, and how hard it is to get rid of legacy code" at
 * https://vanilla-java.github.io/2017/04/13/String-Buffer-and-how-hard-it-is-to-get-rid-of-legacy-code.html
 */
public class Main
{
   /**
    * Main function that instantiates this Java "application" and does nothing
    * else until "ENTER" is pressed.
    */
   public static void main(final String[] args) throws IOException
   {
      System.out.println("Waiting [press ENTER to exit] ..");
      System.in.read();
   }
}

The following screen snapshot shows the output of using jcmd with its -all option (includes unreachable objects in the inspection) to show the number of instances of StringBuffer and StringBuilder in the simple Java application when compiled and run against three different versions of Java (Java 8 Update 102, Java 8 Update 121, and OpenJDK 9.0 ea+164). The execution of jcmd is performed in PowerShell and so Select-String is used similarly to how grep is used in Linux.

Although the versions of the class compiled and executed with versions of Java 8 had instances of StringBuffer, the version compiled with and executed against Java 9 only had instances of StringBuilder. It looks like the resolution of JDK-8041679 ("Replace uses of StringBuffer with StringBuilder within core library classes") and JDK-8043342 ("Replace uses of StringBuffer with StringBuilder within crypto code") have had their intended effect.

Monday, April 25, 2011

Posts of Particular Interest: Java and JavaOne, PHP, PowerShell,

In this post, I reference and briefly some posts of particular interest to me in recent weeks. Posts referenced here cover topics such as Java (JavaOne, JMX, Java Memory), PHP, and PowerShell.


Top Java Memory Problems

Michael Kopp's The Top Java Memory Problems – Part 1 provides a nice overview of common memory issues in Java applications. Specifically, he covers memory leaks related to thread local variables, mutable static fields and collections, circular/bi-directional references, JNI, improper equals/hashCode implementations, and classloaders.


Three Free E-books on Beginning Java (and Five on PHP)

Klint Finley's post 3 Free E-Books on Java for Beginners references three freely available e-books about Java. I was already aware of Bruce Eckel's Thinking in Java (as usual, he offers the second newest edition free of charge), but he also mentions How to Think Like a Computer Scientist: Java Edition and Introduction to Programming in Java.

In a related post called 5 Free E-Books and Tutorials for Learning PHP, Finley outlines five freely available PHP resources. As I recently posted, I have plans to start learning and working with PHP, so this post interests me.


Best JVM Replacement Language is Java? (and the Play Framework)

In the post And the best JVM replacement language for Java is: Java?, Mark Watson talks about some of the strengths of Java and discusses things he does "to make Java more agile." He also mentions early satisfaction with the Play framework. In one of the feedback comments on this post, Steven states, "I had to leave Java for the Rails-type frameworks because of the productivity gains. I have to say that with Play! you get the best of both worlds."


Accessing JMX on the Web with Jolokia

In the post Jolokia + Highcharts = JMX for human beings, Tomasz Nurkiewicz writes about using Jolokia ("HTTP/JSON bridge for remote JMX access") in conjunction with Highcharts ("free for noncommercial") to display JMX-provided JVM metrics in a web browser application. There are generic tools such as VisualVM and JConsole that can do some of this, but the flexibility and customizability of an approach like that demonstrated by Nurkiewicz can provide significant advantages in certain situations.


Actors and GPars

Vaclav Pech's Dr. Dobb's Journal article JVM Concurrency and Actors with GPars discusses how GPars (Groovy Parallel Systems) allows actors to be used on the JVM to simulate continuations. As Pech demonstrates this, he also covers highly-related topics such as basics of the actor model, an introduction to GPars for use in Groovy or Java or any JVM language, and lists other features provided by GPars.


PowerShell Language Licensed Under the Community Promise

The Windows PowerShell Blog post PowerShell Language now licensed under the Community Promise states:
The PowerShell team is excited to announce that starting today we are licensing the language specification for Windows PowerShell 2.0 under the Microsoft Community Promise. This means that now anyone can implement PowerShell on any platform they want to.
The specification is available for free download as a docx file.


JavaOne 2011 Formally Announced

There were multiple posts on JavaOne 2011's formal announcement. The JavaOne 2011 post in The Java Source blog and the JavaOne Conference Blog post JavaOne 2011 - October 2nd to 6th in San Francisco confirm that JavaOne 2011 will be held October 2-6, 2011, in San Francisco. This announcement also headlines the DZone Daily Dose and is featured in Java.net's "Spotlights" section.


Conclusion

There's much going on in the world of software development in general and the world of JVM development in particular. The posts I cited above are evidence of this and it is particularly exciting to see fresh new posts on subjects such as JMX, JVM actors with GPars, in-depth coverage of Java memory issues, and so forth.

Saturday, March 22, 2008

Comparing Unix/Linux, PowerShell, and DOS Commands

The following lists some of my favorite Unix commands and maps the associated PowerShell and DOS commands, if any. If there is one Unix command I would love to have in PowerShell, it is the grep command with its regular expression support. I have noticed significant improvement in Vista's search capabilities compared to earlier versions of Microsoft operating systems that I have used and I would love to see that harnessed in PowerShell so that I could use it from the command line. The table appears a ways down, so scroll down to it.

UPDATE (24 March 2008): Note that I have updated this table with information on a grep equivalent and on the availability of less as an extension. Thanks to Kirk Munro for pointing both of these out (see Comments) and to Jeffrey Snover for his write-up of Select-String at http://blogs.msdn.com/powershell/archive/2008/03/23/select-string-and-grep.aspx.
Thanks also to Marco Shaw for pointing out that start-transcript (which can be closed with stop-transcript) provides functionality like Unix's script command. Thanks to Jonathan for mentioning tasklist as an alternative to ps and mentioning F7 for a graphical presentation of history commands.
























Unix/LinuxPowerShellWindows Vista DOS
lsls
dir
dir
cpcp
copy
copy
mvmv
move
move
rmrm
del
del
netstatnetstatnetstat
manman
help
help
psps
tasklist
tasklist
fingerfingerfinger
script
(stop with CTRL-D)
start-transcript
(stop with stop-transcript)
 
clearclear
cls
cls
catcat
type
type
history / hhistory / h
F7
F7
unzipunzipunzip
zipzipzip
teetee 
grepSelect-String 
moremoremore
lessless (extension) 
editeditedit
killkill
taskkill
taskkill


Type ‘man’ without any options in PowerShell command-line
to see long list of supported commands and scripting keywords.



The Windows PowerShell Quick Reference and Getting Started with Windows PowerShell are also useful resources.

Saturday, February 23, 2008

Windows PowerShell and Java

In my previous blog entry, I briefly wrote about Windows PowerShell. In this blog entry, I intend to cover some uses of Java with Windows PowerShell.

Many Java applications require the environment variable JAVA_HOME to be set appropriately to work correctly. In PowerShell, you can check the setting of a particular environment variable with the command echo $env:JAVA_HOME. An example of this is shown in the next screen snapshot (click on image to see larger version).



Another environment variable that is often useful to note when using Java is any CLASSPATH setting. This can be checked with the echo $env:CLASSPATH command. If the CLASSPATH environment variable is set, it will be displayed. What if you wanted to set your classpath for use in Java applications rather than passing the classpath to the application with the Java launcher? In that case, you could set CLASSPATH with the command $env:CLASSPATH = "<<someClassPath>>".

The quotation marks are significant in setting the classpath because the semicolon (;) is still used to separate class path entries. Because the semicolon also tells PowerShell that a command is being terminated and another started, this must be in quotation marks to avoid the classpath being treated as two separate statements.

The classpath can also be set on the command-line in conjunction with the Java launcher with a command like: java -cp "<<someClassPathEntry>>;<<anotherClassPathEntry>>" <<package>>.<<classToRun>> (again, as with setting the CLASSPATH environment variable, quotations should be used around the entire classpath entry so that the semicolon is not treated as a statement terminator). A concrete example of this is shown next:

java -cp "C:\NetBeansProjects\SpringJmxExample\build\classes;C:\spring-framework-2.5.1\dist\spring.jar;C:\spring-framework-2.5.1\lib\jakarta-commons\commons-logging.jar" marx.SpringJmxMain


The take-aways from all of this include the following:

  • Although many Unix-isms can be used in PowerShell, one should still use the semicolon for classpath separators as described in the Windows Setting the Class Path document rather than with colons for Unix as documented in the Solaris Setting the Class Path document.

  • PowerShell does recognize semicolons as statement terminators for placing multiple statements on the same line. This very Unix-like feature means that class path values must be surrounded in quotes so that multiple entries can be separated with semicolons without making PowerShell think there are multiple statements on the line.

  • Although PowerShell "feels" much more like Unix than DOS, it still supports DOS operations and the semicolon and backwards slashes in the examples above shown that this is the same as in DOS as well. That being said, I can also use more Unix-like syntax and have it work as well. The command shown above could also be run as follows:

    java -cp "/NetBeansProjects/SpringJmxExample/build/classes;/spring-framework-2.5.1/dist/spring.jar;/spring-framework-2.5.1/lib/jakarta-commons/commons-logging.jar"
    marx.SpringJmxMain

    The above command will behave exactly as the one shown above, but without the DOS-obvious C:\ drive syntax and the backwards slashes.

  • It is not shown above, but you can find out more about using PowerShell environment variables by running the command man env (or help env) in the PowerShell terminal window.



When specifying Java system properties on the command line in PowerShell, you need to put quotation marks around the these specifications so that the -D is not interpreted prematurely. The next screen snapshot shows running Java with the -D system properties options without quotes and the error that follows. The same screen snapshot then shows how it runs successfully if double quotes are used around the -D system properties.



You can run the java -version command in PowerShell just as you would in DOS or Unix/Linux. The next screen snapshot demonstrates this.



Similarly, you can run other Java executable tools in the same way you'd run them in DOS or in Unix/Linux. The next screen snapshot shows the command-line view of running these in PowerShell.



PowerShell brings each of us a more "natural" Java development command-line experience if we've developed Java primarily in a Unix/Linux environment in the past.

It is not as easy as I would have expected to find good blogs and articles on using Java with PowerShell. This may be due somewhat to the chasm that often seems to exist between the Windows community and Java or other non-.NET communities. Here are some interesting links related to using Java with PowerShell:

Hello Windows PowerShell

I have been frustrated for some time with DOS scripting. Fortunately, a colleague pointed me to Microsoft PowerShell (formerly known as Project Monad) for Windows XP and Windows Vista. PowerShell can be downloaded here and there are several scripts for use with PowerShell provided here. You can also download the Windows PowerShell Owner's Manual.

One of the things that is nice about PowerShell is that is supports many of the commands that we like to use in Unix/Linux. There are far too many useful things to demonstrate about PowerShell in one place, but the next two screenshots (click on them to see larger versions) demonstrate some Unix-like commands supported in Windows PowerShell.

The first screen snapshot demonstrates the very handy history command along with the ability to run a man (equivalent to help) command for a particular command.



The next screen snapshot shows the ls command along with the mv command. Having Unix equivalents makes it less frustrating to switch between Unix/Linux and Windows. Also, the ls and mkdir commands demonstrate the displaying of file modes.



Besides the Unix/Linux commands shown in the screen snapshots above, other goodies that are now available in PowerShell include pwd, ps, and cat. It is amazing how nice it is to have these little "extras" in the DOS scripting world.

Windows PowerShell requires .NET framework 2.0, so you'll need to get this if you don't already have it. There is much, much more to Windows PowerShell than what I've shown here so far. I think it is likely that I'll post future blog entries on other great features of PowerShell. It is even more likely that I'll start using PowerShell more frequently in my blog entries that show me running scripts, Java commands, the Flex compiler, etc. from the command line rather than using the old-style DOS terminal.

In related resources, Vaibhav discusses running PowerShell from Java. An interesting related article is A Return to Command-Line Control with Windows PowerShell. A free Windows PowerShell eBook is available as well. Finally, two other introductory references for using PowerShell are What is Windows PowerShell? and Top Ten Tips for Using Windows PowerShell Finally, a gentle introduction to Windows PowerShell is available in Discover PowerShell.