#460 To aggressive when optimizing code concerned with volatile fields?



I'm the author of HaikuVM (a Java VM for Atmel AVRs and other micros using the leJOS runtime).
I try to use ProGuard as bytecode optimizer. Doing this I encountered a problem when it comes to volatile fields.

In the following code example the native readSensors() method updates the sensor01 field (and other fields) every time the method is called. ProGuard - not knowing about this native behavior - assumes that sensor01 keeps its value of 0 for ever. Consequently ProGuard optimizes away the if-block.

public class OptimizedVolatiles {
private static volatile int sensor01;

private native static void readSensors();

public static void main(String[] args) {
    while (true) {
        if (sensor01>0)  { // this if-block is optimized away
            System.out.println("Sensor01 value is "+sensor01);


IMHO (don't knowing what JAVA volatile-definitions are telling about this) ProGuard is to aggressive when optimizing code concerned with volatile fields.


  • Eric Lafortune

    Eric Lafortune - 2013-01-20

    Thanks for your report -- nice project.

    ProGuard processes code with a closed-world assumption. It can't know some external code (in this case, native code) is modifying the field (volatile or not), unless you tell it:

    -keepclassmembers class somepackage.OptimizedVolatiles {
        int sensor01;

    In general, ProGuard is careful about optimizing busy-waiting loops on volatile fields that may be written from known code.

    If this doesn't solve the issue, I'll have to investigate further.

  • Eric Lafortune

    Eric Lafortune - 2013-01-20
    • status: open --> open-works-for-me
    • assigned_to: Eric Lafortune
  • genom2

    genom2 - 2013-01-20

    Thank you for your prompt response. I already found a solution that worked for HaikuVM (but the one you gave is better). I just put this issue into this bug forum because I think it's a principle one.

    I think augmenting a variable with 'volatile' breaks your 'closed-world' working hypothesis. (But still not knowing what JAVA volatile-definitions are telling about this.)

    But what I really want to say is, that your project: ProGuard overwhelmed me.

  • Eric Lafortune

    Eric Lafortune - 2013-03-20
    • Status: open-works-for-me --> closed-works-for-me

Log in to post a comment.