Question

I am writing a Java ME application now. As I know, it uses old Java Memory Model, because its features are restrictred to Java 1.3. The only guarantee about volatile keyword this model provides is that all reads and writes go directly through main memory and are not cached.

Consider following code:

class BillHelper {
    volatile HttpConnection con;
    volatile InputStream in;

    // Called from thread A
    BillResponse makeBill(BillRequest request) throws BillException {
        // open http connection
        // extract request data from method parameter
        // prepare all needed headers
        // flush headers
        // open input stream, parse response
    }

    // Called from thread B
    void cancelBillRequest() {
        if (in != null) {            
            try {
               in.close();
            } catch (IOException ignored) {}
        }

        if (con != null) {  
            try {
               con.close();
            } catch (IOException ignored) {}
        }
    }
}

Methods are called from different threads. Method makeBill() writes to the volatile variables, method cancelBillRequest() reads from that fields.

Is declaring two fields volatile sufficient? What can you say about volatile reads and writes reordering? Is my code safe?

Was it helpful?

Solution

Don't depend on volatile doing anything. The old memory model was broken, which is why there is a new one.

Synchronize access to your fields with an object. That is the only way you can guarantee write/read safety. (i.e. Object obj = new Object(); and in each method: synchronized (obj) {} )

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top