Categories
Java

Using reflection with arrays and primitive types

Sometimes it is necessary to handle a parameter of type object different for the real type. So you have to use instanceof to determine the type of an object. If you are need to check if it is an array, you can use the Reflection-API provided by the JRE. The Reflection API is a comfortable and rich functional API to inspect and manipulate Objects at runtime. One example could be to access private fields at runtime.

I had the problem to serialize some variables to JavaScript, so I wrote me a simple function:

1
public void objectToJavaScript(Object object, StringBuffer buf);

If the given object is primitive I would simple add it to the provided StringBuffer, but if it is an array I need to output ‘[‘ and ‘]’ with the given parameters. So I have to check if the object is an array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void objectToJavaScript(Object object, StringBuffer buf) {
    if (object == null) {
        buf.append("null");
        return;
    }
    ... //other types
    if (object.getClass().isArray()) {
        buf.append('[');
        //TODO output array content
        buf.append(']');
        return;
    }
    ...
}

But how to access each entry of the array? One way could be to cast the object to Object[]. Unfortunately if the array is an array of primtive types this would throw a ClassCastException. So we have to use the functions, provided by java.lang.reflect.Array. The full code looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void objectToJavaScript(Object object, StringBuffer buf) {
    if (object == null) {
        buf.append("null");
        return;
    }
    ... //other types
    if (object.getClass().isArray()) {
        buf.append('[');
        int len = java.lang.reflect.Array.getLength(object);
        for(int i = 0; i < len; i++) {
            if (i > 0) buf.append(',');
            objectToJavaScript(java.lang.reflect.Array.get(object, i), buf);
        }
        buf.append(']');
        return;
    }
    ...
}
Categories
Java

comfortable thread pools using java.util.concurrent

Today I had another time the problem to execute many short tasks in a thread pooled environment. One way could be to write the pooling itselfs (like the other times in history ;)). But I thought: Why to reinvent the wheel every time and not using standardized libraries like the java.util.concurrent.*?

What I want:

  • A self enlarging and shrinking ThreadPool depending on the queued tasks. (Because sometimes it is nothing to do and sometimes it could be to get many hundreds of tasks in a short time)
  • A definable Limit of maximum running Threads (Because we cannot create hundreds of threads just for this task. Keep in mind: the tasks have a short run time)
  • Queuing the Tasks to run later, if the ThreadPool has reached the given limits

So I looked at the given Examples and the Executors-Class, which provides fast and simple methods:

  1. newCachedThreadPool : This looks good, but unfortunately you can’t define a maximum limit of threads.
  2. newFixedThreadPool : This handles the wanted limitation, but not the automatic enlarging and shrinking.

So we cannot use the predefined methods and need to instantiate ThreadPoolExecutor directly.

Categories
Javascript JQuery

Preloading Images with JavaScript

Sometimes in a complex javascript-application you want to display an image when it is fully loaded. Until then you want to show for example a common loading-imageAjax Loading Image. In this case the best solution is to load the image in background, and then show it to the use. For that you can use the Image-Class provided by the browsers.

This class is the used Class at img-Tags. So you have all known properties, like “src”. With the onload-Event you can then check, if the image was fully loaded or not. An example would be:

?View Code JAVASCRIPT
1
2
3
var image = new Image();
$(image).load(function () { alert("picture is fully loaded."); });
image.src="http://www.javahelp.info/wp-content/uploads/2009/11/Bild-80-300x64.png";

In the example I use JQuery for event-handling, because this is more comfortable as the normal event-method of JavaScript.

Categories
Java

Java 5 – End of Service Life (EOSL)

The Standard Service Life of Java 5 expired on Friday, October 30th. This is not really tradic, because Sun provides a Java SE 6 since December 2006. But on the other side on Mac OS X (up to 10.5. Leopoard) the default JRE is Version 5.0. Standard Java Version on Mac OS X 10.5
Apple only published a Version 6 for 64 bit Intel processors. So many desktop applications still uses Java 5 as basis. It would be interessting, what Apple will do, if critical bugs in Java 5 would be found.

An overview of the whole EOL-Policy for Java can be seen at http://java.sun.com/products/archive/eol.policy.html

Categories
Java JBoss

Using TransactionAttribute in submethods on same EJB3-Beans

The EJB3 Standard provides some annotations to handle general approaches, like transactions (@TransactionAttribute) and security (@RolesAllowed, etc.). To use these methods, you only have to add them to the concerning method.

1
2
3
4
5
6
7
8
@Stateless
@Local(SampleStateless.class)
public class SampleStatelessBean implements SampleStateless {
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void sampleMethod() {
        // do some stuff
    }
}

Sometimes you have to call methods of other business objects to handle the business logic. For example you have a batch update separated into many small update steps. Here you want to split the main transaction into several small transactions and the main part should have no transaction, because it only handles the reading of external data (The example code is not complete and should only demonstrate the usage of the annotations.).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Stateless
@Local(SampleStateless.class)
public class SampleStatelessBean implements SampleStateless {
    @TransactionAttribute(TransactionAttributeType.NEVER)
    public void import() {
       //read some data
       while (haveData) {
           importData(subData);
       }
    }
 
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    private void importData(List data) {
        // do some stuff
    }
}

This above code is unfortunately NOT CORRECT. The reason is that the @TransactionAttribute-annotations will only be honored, if you call the method via a business interface. So the first solutions is to inject the bean itself and call the submethod via the injected bean.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Stateless
@Local(SampleStateless.class)
public class SampleStatelessBean implements SampleStateless {
    @EJB
    private SampleStateless bp;
 
    @TransactionAttribute(TransactionAttributeType.NEVER)
    public void import() {
       //read some data
       while (haveData) {
           bp.importData(subData);
       }
    }
 
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void importData(List data) {
        // do some stuff
    }
}

Another solution, which is quite faster on JBoss in my tests, is to use the SessionContext to get a reference to the current business object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Stateless
@Local(SampleStateless.class)
public class SampleStatelessBean implements SampleStateless {
    private SampleStateless bp;
 
    @Resource
    private SessionContext ctx;
 
    @PostConstruct
    public void init() {
        bp = ctx.getBusinessObject(SampleStateless.class);
    }
 
    @TransactionAttribute(TransactionAttributeType.NEVER)
    public void import() {
       //read some data
       while (haveData) {
           bp.importData(subData);
       }
    }
 
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void importData(List data) {
        // do some stuff
    }
}