Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the correct way to synchronize a shared, static object in Java?
    text
    copied!<p>This is a question concerning what is the proper way to synchronize a shared object in java. One caveat is that the object that I want to share must be accessed from static methods. My question is, If I synchronize on a static field, does that lock the class the field belongs to similar to the way a synchronized static method would? Or, will this only lock the field itself?</p> <p>In my specific example I am asking: Will calling PayloadService.getPayload() or PayloadService.setPayload() lock PayloadService.payload? Or will it lock the entire PayloadService class?</p> <pre><code>public class PayloadService extends Service { private static PayloadDTO payload = new PayloadDTO(); public static void setPayload(PayloadDTO payload){ synchronized(PayloadService.payload){ PayloadService.payload = payload; } } public static PayloadDTO getPayload() { synchronized(PayloadService.payload){ return PayloadService.payload ; } } ... </code></pre> <p>Is this a correct/acceptable approach ? </p> <p>In my example the PayloadService is a separate thread, updating the payload object at regular intervals - other threads need to call PayloadService.getPayload() at random intervals to get the latest data and I need to make sure that they don't lock the PayloadService from carrying out its timer task</p> <p>Based on the responses, I refactored to the following:</p> <pre><code>public class PayloadHolder { private static PayloadHolder holder; private static PayloadDTO payload; private PayloadHolder(){ } public static synchronized PayloadHolder getInstance(){ if(holder == null){ holder = new PayloadHolder(); } return holder; } public static synchronized void initPayload(){ PayloadHolder.payload = new PayloadDTO(); } public static synchronized PayloadDTO getPayload() { return payload; } public static synchronized void setPayload(PayloadDTO p) { PayloadHolder.payload = p; } } public class PayloadService extends Service { private static PayloadHolder payloadHolder = PayloadHolder.getInstance(); public static void initPayload(){ PayloadHolder.initPayload(); } public static void setPayload(PayloadDTO payload){ PayloadHolder.setPayload(payload); } public static PayloadDTO getPayload() { return PayloadHolder.getPayload(); } ... </code></pre> <p>Is this approach legitimate? I am also curious if it is better to do it this way or using the AtomicReference approach mentioned by Hardcoded ...? - I am keeping an instance of PayloadHolder on PayloadService simply to keep a reference to the PayloadHolder class active in the jvm for as long as the PayloadService is running.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload