SmartSolution
SmartSolution

Reputation: 2338

Is java native method calls are Atomic calls?

I need certain operation to be Atomic.

Here 'Atomic' means to say "once that method started execution, it shouldn't be interrupted till it finishes, And even thread scheduler also should not make that thread to Runnable state once its in Running state".

All methods are Native methods and multiple threads are running concurrently to execute these methods.

First Question: Is the native methods execution is Atomic in nature?

Second Question : To achieve the Atomicity, Can we use java concurent/lock APIs, if yes, please provide any example/link if possible?

Thanks.

Upvotes: 3

Views: 1233

Answers (3)

Michael Kutschke
Michael Kutschke

Reputation: 221

If i understand the question right, you are asking for: Is it possible for me to achieve that a certain thread will always be running on the CPU until it is finished? To be clear, it should not be replaced by another thread during that time.

The answer is: Even if it was (and i don't think it is), this would have nothing to do with atomicity. Because if you have multiple CPU's, multiple Threads can still access and change the same data while all are truely running uninterrupted at the same time. Therefore, even with your definition of "atomicity", you would still end-up with concurrency problems.

If you just want thread-safety in the conventional sense, then yes, you can use java-locks etc. to achieve that, even if you call native methods. see http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/sync.html for an example of java thread synchronization from within native methods.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533472

To prevent an interrupt you must the the machine code instructions cli and sti to disable and enable interrupts (on x86/x64). It not something you can even do in plain C language.

This is so low level as it is rarely done. Largely because its rarely very useful. The main concern is usually the behaviour of interaction with other threads which is why Atomic is defined this way for most use cases, not atomic in terms of interrupts.

Upvotes: 1

emory
emory

Reputation: 10891

Your definition of atomic is non-standard. This is a more standard definition.

  1. Are native methods atomic (by your non standard definition)? Since I could at any point during the operation of a native method, yank the power cord and interrupt execution, I would say that native methods are incorrigibly non atomic.
  2. Can we use the java concurrent lock APIs to achieve atomicity (non standard) in native methods? As stated previously, native methods are incorrigibly non atomic. Nothing can help.

Upvotes: -1

Related Questions