Replacement for synchronized()?


I’m confused.

I 've always used

(Example: take something from a queue if present, or else construct new instance).

I want to use this for a common-code library class (where I have no idea if it might be used in a multi-thread app).

I find that the use of synchronized(,) is now deprecated in JVM and not supported in JS.
The @Synchronized annotation also cannot be used.

Is there a technique which I can use in common code and will ensure single-thread access to critical code when on a JVM / Native platform?


I do not think there is any common-platform locking mechanisms in the standard library. I recommend that you try to write your common code such that it does not use shared state, and then deal with the concurrency aspects in platform specific code.

As for which synchronization mechanisms that are available on each platform:

  • On JVM you can use locks from package java.util.concurrent.locks.
  • JS does not have threads in the classical sense. Instead it has workers, which cannot share state. So here it is not a problem
  • On native targets, you will need to use whichever concurrency tools that are available on that platform. POSIX is probably the one that is supported on most platforms.



Thanks, Mike.
Now I just have to solve the problem of running JUnit tests on the ‘common’ library.