I was getting Out of Memory Error: can't create native thread errors on a server, and it was definately not running out of memory, so I hacked this little program together to tell me how many threads I should be able to create.

64K is the minimum stack size that Java will allow on an Intel platform. OSX 10.6.3 Snow Leopard has a hard coded limit of 2560 threads. Leopard Server doesn’t seem to have this limit.
TestThreadStackSize.java

public class TestThreadStackSizes
{
    public static void main(final String[] args)
    {
        Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(final Thread t, final Throwable e)
            {
                System.err.println(e.getMessage());
                System.exit(1);
            }
        });
        int numThreads = 1000;
        if (args.length == 1)
        {
            numThreads = Integer.parseInt(args[0]);
        }

        for (int i = 0; i < numThreads; i++)
        {
            try
            {
                Thread t = new Thread(new SleeperThread());
                t.start();
            }
            catch (final OutOfMemoryError e)
            {
                throw new RuntimeException(String.format("Out of Memory Error on Thread %d", i), e);
            }
        }
    }

    private static class SleeperThread implements Runnable
    {
        public void run()
        {
            try
            {
                Thread.sleep(1000 * 60 * 60);
            }
            catch (final InterruptedException e)
            {
                throw new RuntimeException(e);
            }
        }
    }
}

 

Here is a basic class to connect to a Glassfish 2.1.x JMS Queue from a command line client.

You need the following .jar files in your CLASSPATH for the code below to work.
.../glassfish/imq/lib/imq.jar
.../glassfish/imq/lib/imqutil.jar
.../glassfish/imq/lib/jms.jar
.../glassfish/lib/appserv-admin.jar
.../glassfish/lib/appserv-rt.jar
.../glassfish/lib/j2ee.jar
.../glassfish/lib/javaee.jar

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;

public class Main
{
    public static void main(final String[] args)
    {
        Context jndiContext;
        ConnectionFactory connectionFactory;
        Connection connection;
        Session session;

        Queue queue;
        MessageProducer messageProducer;
        TextMessage message;

        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.appserv.naming.S1ASCtxFactory");
        properties.put(Context.PROVIDER_URL, "iiop://127.0.0.1:3700"); // had to use ip address, localhost didn’t work

        try
        {
            jndiContext = new InitialContext(properties);
            connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/ConnectionFactory"); // put your ConnectionFactory here
            queue = (Queue) jndiContext.lookup("jms/Queue"); // put your Queue here
            connection = connectionFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            messageProducer = session.createProducer(queue);
            message = session.createTextMessage("Hello World!");
            messageProducer.send(message);
            connection.close();
        }
        catch (JMSException e)
        {
            throw new RuntimeException(e);
        }
        catch (NamingException e)
        {
            throw new RuntimeException(e);
        }
        System.exit(0);
    }
}

 

I have to parse the TXT records from DNS responses for my inet_mdns project. The valid key values pairs look like one of the following three formats:
"key=value"
"key=" ( key with an empty/no value )
"key" means the same thing as "key=true"

so in Java I would write something like.

public String processKeyValue(final String kv)
{
    return kv.split("=").length == 1 ? kv + "=true" : kv ;
}

And then I could process all the versions the same to build a dictionary / map out of the keys and values. This is a one line in Erlang, and not only does it prepare the string for splitting into a key and value, it does the splitting!

F = fun(T) -> case re:split(T,"=",[{return,list}]) of [K] -> {K,true}; [K,V] -> {K,V} end end.

The more I learn about Erlang the more I really appreciate how powerful functional programming paradigms are. Here is what the output looks from the Erlang shell.

Eshell V5.7.3  (abort with ^G)
1> F = fun(T) -> case re:split(T,"=",[{return,list}]) of [K] -> {K,true}; [K,V] -> {K,V} end end.
#Fun<erl_eval.6.13229925>
2> F("key").
{"key",true}
3> F("key=value").
{"key","value"}
4> F("key=").
{"key",[]}
5>

so to simulate a Ternary operation in Erlang use a case statement like the following.

case <boolean expression> of
    true ->
        <what to return when true>;
    false ->
        <what to return when false>.

is the same as

<boolean expression> ? <true case> : <false case>;

It is probably best practices to wrap the above code in a function or fun() if it needs to be passed around, instead of embedding case statements in your code. It will at least be more re-usuable that way.

 

By default Java 1.6 caches DNS queries, either forever if there is a security manager installed or for an implementation specific period if there is no security manager installed. There are two ways to disable this behavior which breaks things like load balancers that do DNS load balancing.

first you can disable it by adding -Dsun.net.inetaddr.ttl=0 on your command line when starting the JVM.
A prefered way is to add the property networkaddress.cache.ttl=0 to your %JRE%/lib/security/java.security file.
Or you can set the value in code with java.security.Security.setProperty("networkaddress.cache.ttl", "0" );

 

One of the most useful things you can do for any project is provide command line friendly tools for administration, diagnostics and maintenance. As nice as browser based administration tools are, not everyone has access to production machines behind firewalls and the sort with a browser, most administration is done via ssh. Giving operations tools that they can interconnect with normal Unix development tools makes their life and your life a whole lot better. They can build the tools they need with the foundation tools you provide.

In the past I have written most of my command line programs in Python. It is batteries included, standard on any Unix or Linux distribution worth using, and it just works. I have recently been introduced to Groovy and have been using it to produce some very sophisticated tools in a very short period of time.

But one of the downsides is that it inherits all the deployment difficulties of Java as well as all the benefits like the extensive standard library and third party code available. Even as easy as it is to add Groovy to the Extensions directory of your JDK installation, it doesn’t help your end users who might not know how to do such a thing. Everyone loves a standalone executable. Having to add a bunch of .jar files to your CLASSPATH environment variable isn’t any better or portable. Wrapper shell scripts aren’t a perfect solution either, bash is pretty ubiquitous, but not everyone uses bash, and what about Windows?

The best solution is to bundle your application with all its dependencies in a single .jar file. For most things this is a great way to distribute command line tools to hosting operations personnel and other end users that might not be Java experts. But this isn’t the easiest thing to accomplish with the basic jar tool that sun provides. Here I present a simple Ant based solution that can be modified and used to bundle any code base up into a standalone executable .jar file that can be executed on any platform that support Java, without any of the dependencies needing to be installed before hand.

Here is a basic build-jar target.

<target name="build-jar" depends="compile">
    <jar destfile="${dist.dir}/app.jar" compress="true">
        <manifest>
            <attribute name="Main-Class" value="main"/>
        </manifest>
        <fileset dir="${build.dir}/classes" includes="**/*.class"/>
        <zipgroupfileset dir="${lib.dir}">
            <includesfile name="dependencies.list"/>
        </zipgroupfileset>
    </jar>
</target>

What this will do is it wil include all the contents of the .jar files listed in dependencies.list file that is in your ${lib.dir} in with your .class files from your ${build.dir}/classes directory and set the default executable class to main. The dependencies.list is just a plain text file with the name of each .jar file to include on each on a separate line. Here is an example.

JSAP-2.1.jar
xstream-1.3.1.jar
groovy-all-1.6.5.jar
mysql-connector-java-5.1.7.jar
ojdbc-10.2.0.4.0.jar
© 2012 Jarrod Roberson: Programming Missives Suffusion theme by Sayontan Sinha