Method parameter thread safety in Java

I would like to know if thread safety plays when handling element parameters in Java.

Let's say you have an API method

boolean moreThanTen(long value) { if(value > 10) return true; else return false; } 

will this method be a safe thread?

I assume that since each thread has its own stack for local variables, and the primitives are stored in this local stack.

The only thing that makes me unsure is the fact that long will be two separate reads and, as a rule, is not thread safe.

My question is: can I be sure that the method parameter is copied atomically? Therefore, when using a primitive as a parameter (even float / long ), I can be sure that when copying it to a local variable, thread safety will not be a problem?

Thanks.

+5
source share
2 answers

To be unsafe, a method must allow multiple threads to access shared resources (for example, a field).

In your example, there are no shared resources (java passes arguments by value), so the method cannot be unsafe.

This will be unsafe because threshold is accessible from more than one thread, and variable calls are not correctly synchronized:

  • the thread can read the threshold variable while it is being updated by another thread, which can lead to inconsistent reading ( long records are not guaranteed to be atomic ); and
  • writing to the threshold variable from one stream may not be visible from another stream due to lack of synchronization, which may lead to the second stream reading the outdated value.
 private long threshold; //mutable, may change boolean moreThanThreshold(long value) { return value > threshold; //side comment: cleaner than your if/else } void setThreshold(long t) { this.threshold = t; } 
+8
source

In this case, there are no problems with threads. All reads occur in the methods of its own stack. In short, although they are two reads ... they occur on a value inside the stack that is not used among other threads.

Below is a more detailed description of why two reads are not a problem.

When passing arguments to the method, we DO NOT pass the reference variable, but a copy of the bits in the reference variable. Something like this: 3bad086a. 3bad086a represents a way to access the passed object. Therefore, we simply pass 3bad086a that this is the value of the link. We pass the value of the link, not the link (not the object). This value is actually COPIED and passed to the method. We always pass a copy of the link value bit! If it is a primitive data type, these bits will contain the value of the most primitive data type. If it is an object, the bits will contain an address value that tells the JVM how to get to the object.

+1
source

All Articles