"functional way to implement a thread safe shared counter" Code Answer

3

is this thread safe by any chance?

no, unless you have already created the immutable object in a synchronized block, this is not thread-safe. there are chances of creating a corrupt immutable object under thread race condition.

and to achieve the same functionality you can use atomicinteger which avoids explicit synchronization.

public class servlet extends httpservlet {

  public atomicinteger incrementer = new atomicinteger (0);

  @override
  public void service(servletrequest req, servletresponse res) throws ... {
    int newvalue = incrementer.incrementandget();
    super.service(req, res);
  }
}
By Michael Petychakis on May 28 2022

Answers related to “functional way to implement a thread safe shared counter”

Only authorized users can answer the Search term. Please sign in first, or register a free account.