I am currently writing a Java ME application. As I know, it uses the old Java memory model because its functions are limited to Java 1.3. The only guarantee for the volatile keyword in this model is that all reads and writes go directly through main memory and are not cached.
Consider the 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. The makeBill() method writes volatile to the variables, the cancelBillRequest() method reads from these fields.
Declares two volatile fields enough ? What can you say about volatile reads and writes reordering ? Is my code safe?
user961548
source share