1

In Java I can declare synchronized method like this:

public int synchronized myMethod () {
    int i = 0;
    i++;
    return i;
}

This prevents two or more threads to concurrently entering the method (i.e. other threads will wait until the blocking thread finishes). Is there a similar concept in Javascript/AngularJS?

ps0604
  • 1,227
  • 23
  • 133
  • 330
  • possible duplicate of [Concurrency in Angularjs](http://stackoverflow.com/questions/21263564/concurrency-in-angularjs) – jwatts1980 May 05 '15 at 15:35

1 Answers1

1

There is no need for synchronised methods in Javascript, as it's strictly single threaded. While a method is running, there is no other thread running any code.

(The exception from being single threaded would be background workers, but they don't share data with the main thread.)

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • If my method makes an http request and waits for the response, it means that no other methods will run until the first method receives the response and continues/finalizes running the method? – ps0604 May 05 '15 at 15:48
  • No, it means that, until the response comes, the javascript scheduler can freely run other javascript. But neither the handler nor the other javascript will interrupt the other. The upside is you never need synchronization objects. The downside is that if you accidentally code an infinite loop that never gives up control, you will make your page unresponsive. – Michael Hays May 05 '15 at 16:07
  • @pgschr: If you make a request and wait for the response (synchronous request), then no other code will run in the meantime. The browser will also freeze while waiting for the response. If you make an asynchronous request, then the response is handled in an event handler. The event handler will run as soon as the request has arrived, and no other code is running. – Guffa May 05 '15 at 16:19