Synchronized across instances of object - java

I have an object Rotor which has a goalSpeed and a currentSpeed. Each one tries to change its currentSpeed to match the goalSpeed set. I have 4 of these rotors running ing 4 separate threads. Each one gets assigned a new goalSpeed periodically by a controller.
When I attempt in each Rotor to change its currentSpeed, I cannot ever exceed the sum of all rotor's currentSpeed to exceed X value. sum(currentSpeed(Rotor1) + ... + currentSpeed(Rotor2)) !> X.
Here is my issue: when I check wether I can increase the current speed of a Rotor, I make an if statement on the sum of speeds condition. However, it is possible that right after this check, since each rotor is a separate thread that another one changes its value. Therefore my check in the other thread is not valid anymore. How can I make sure that while I'm in the setNewSpeed() method of one rotor, no other rotor will change its current speed?
class Rotor implements Runnable {
private int id;
private int goalSpeed;
private int currentSpeed;
private Controller controller;
private int Y;
private int failedAttempts;
private int successAttempts;
private int maxSpeed;
public int getSuccessAttempts() {
return successAttempts;
}
public void setSuccessAttempts(int successAttempts) {
this.successAttempts = successAttempts;
}
public int getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
public int getFailedAttempts() {
return failedAttempts;
}
public Rotor(Controller c, int Y, int id){
this.controller = c;
this.Y = Y;
this.id = id;
this.currentSpeed = 0;
this.failedAttempts = 0;
this.goalSpeed = 0;
this.maxSpeed = 0;
this.successAttempts = 0;
}
synchronized public void setGoalSpeed(int s){
this.goalSpeed = s;
}
public int getCurrentSpeed(){
return currentSpeed;
}
synchronized private void setNewSpeed(){
int currentDrain = 0;
for(Rotor r : controller.getRotors()){
currentDrain = currentDrain + r.getCurrentSpeed();
}
if((currentDrain + (goalSpeed - currentSpeed)) > 20){
//we cannot increase by total amount because drain too high
System.out.println("failed");
this.failedAttempts++;
currentSpeed = currentSpeed + (20 - currentDrain);
System.out.println("currentSpeed:" + currentSpeed);
} else {
System.out.println("success");
successAttempts++;
currentSpeed = goalSpeed;
}
// System.out.println("goalSpeed:" + goalSpeed);
// System.out.println("currentDrain:" + currentDrain);
}
public void run() {
try {
while(true){
setNewSpeed();
if(currentSpeed > maxSpeed){
maxSpeed = currentSpeed;
}
Thread.sleep(Y);
}
} catch (InterruptedException e) {
System.out.println("Rotor " + id + ": checks=" + (int)(successAttempts + failedAttempts) + ", success rate=" + successAttempts + ", failedAttempts=" + failedAttempts + ", max=" + maxSpeed);
}
}
}

Synchronize on a lock that's shared between all the rotors. Now each of them is synchronizing on their own lock (i.e. this), so even though the method is synchronized, it can be called on different objects at the same time.

The most simple way to synchronize them all is to use a static synchronized method.
That said, using an explicit lock object shared among the instances is probably a better approach.

1) You should not write
synchronized private void setNewSpeed() and synchronized public void setGoalSpeed(int s)
but private synchronized void setNewSpeed() and public synchronized void setGoalSpeed(int s) if you want to respect conventions and standard.
2) You declare two synchronized methods in your Rotor Runnable class but it makes no sense because in the synchronized methods you don't manipulate data shared between the threads.
3) You have multiple ways to address your problem.
A flexible solution consists of using a artificial object shared between the threads and performing the lock on this object when you call the setNewSpeed() method. It allows each tread to wait for the lock to be removed before entering in setNewSpeed().
Here is the idea to implement the solution :
Before instantiating the Rotor, create the shared object in this way :
Object lockObject = new Object();
change public Rotor(Controller c, int Y, int id) to public Rotor(Controller c, int Y, int id, Object lockObject)
invoke the constructor of Rotor by adding the same lockObject instance for all Rotors which you want synchronize between them the speed change.
Store the lockObject as an instance field of the Rotor in the constructor body.
In Rotor use the lockObject to make the synchronization in this way :
sample code :
private void setNewSpeed(){
synchronized(lockObject){
... your actual processing
}
}

Related

Trying to decrement my static count variable in java jdk 1.8.0

Using finalize function, when I point an object to null it’s not decrementing although it is incrementing properly. I also mentioned garbage collector which will listen to its own self, I know but why it’s not working. I am using java jdk 1.8.0.
public class student{
private String name; private int roll; private static int count = 0;
//setters
public void setname(String nam){
name = nam;
}
public void setroll(int rol){
roll = rol;
}
//getters
public String getname(){
return name;
}
public int getroll(){
return roll;
}
public static int getCount(){
return count;
}
//default constructor
public student(){
name = "default";
roll = 9999;
count += 1;
}
//parameterized constructor
public student(String nam, int rol){
setname(nam); setroll(rol);
count += 1;
}
//copy constructor
public student(student s){
name = s.name; roll = s.roll;
count += 1;
}
//methods to print on console
public void print(){
System.out.println("name: " + name + "\n" + "Roll Num: " + roll);
}
// overriding finalize method of Object class
public void finalize(){
count -= 1;
}
}
//main function
public class clsnew{
public static void main(String args[]){
System.out.println("nuber of students" + student.getCount());
student s1 = new student("Ahmad", 170404873);
student s2 = new student();
s1.print(); //printing using parameterized constructor
s2.print(); //printing using default constructor
System.out.println("number of students" + student.getCount());
s2.setname("Ali"); s2.setroll(200404230);
System.out.print("s2: Name = "+s2.getname());
System.out.println("Roll number: "+s2.getroll());
student s3 = new student(s2);
s2.print(); s3.print();
System.out.println("number of students" + student.getCount());
s2 = null;
System.gc();
int c = student.getCount();
System.out.println("number of students" + student.getCount());
}
}
First of all, you should never write applications relying on the garbage collector. Further, even if you need interaction with the garbage collector, you should avoid finalize().
For educational purposes, you have to be aware of the following things:
Finalization is not instantaneous. System.gc() is not guaranteed to identify a particular dead object, or even have an effect at all, but when it does, it may only enqueue the object for finalization, so by the time System.gc() returns, finalization might not have finished yet. It even might not have started yet.
Since the finalizer runs in an arbitrary thread, it requires thread safe updates.
Make the following changes:
Change private static int count = 0; to
private static final AtomicInteger count = new AtomicInteger();,
further count += 1; to count.incrementAndGet(); in each constructor
and count -= 1; to count.decrementAndGet(); in the finalize() method.
And getCount() to
public static int getCount(){
return count.get();
}
Change System.gc(); to
System.gc();
Thread.sleep(100);
You may surround the sleep call with a try...catch block or change the declaration of the main method adding throws InterruptedException
Then, you may observe the finalization of a student instance. To illustrate the counter-intuitive behavior of programs relying on garbage collection, I recommend running the program again, now with the -Xcomp option.
When you have JDK 11 or newer, you might also do a another run with
-XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC.

Adding numbers using multiple threads in java

I am having trouble figuring out what my code is doing as this is my first time coding using multiple threads. To start off, in attempt to learn this type of programming I decided to write a miniature program that uses 8 threads to sum a number. However, no matter what I do it seems as if my program never stops when count = 10, it continues onward. I am using 8 threads as I planned on expanding my program to do large calculations. However, these threads are not correlating at all. They are going way past 10. I have used a synchronized method. I have tried a lock. I have tried implementing both at the same time. No matter what, it appears as if the threads still calculate past 10. See below for my current code.
public class calculator implements Runnable {
static int counter = 0;
static int sum = 0;
private synchronized static int getAndIncrement()
{
// System.out.println("counter is : " + counter);
int temp = counter;
counter = counter + 1;
System.out.println("counter is now : " + counter);
return temp;
}
private synchronized void addToSum(int value)
{
// System.out.println("sum : " + sum + " value: " + value);
sum += value;
}
#Override
public void run()
{
// TODO Auto-generated method stub
while(counter < 10)
{
int tempVal = getAndIncrement();
System.out.println("temp val : " + tempVal);
addToSum(tempVal);
// System.out.println("sum is now : " + sum);
}
}
}
This is my main method:
public static void main(String[] args)
{
calculator[] calc = new calculator[8];
Thread[] thread = new Thread[8];
final long startTime = System.currentTimeMillis();
for(int i = 0; i < 8; i++)
{
calc[i] = new calculator();
thread[i] = new Thread(calc[i]);
thread[i].start();
}
while(thread[0].isAlive() ||thread[1].isAlive() || thread[2].isAlive() || thread[3].isAlive() || thread[4].isAlive() || thread[5].isAlive() || thread[6].isAlive() || thread[7].isAlive())
{}
final long endTime = System.currentTimeMillis();
System.out.println(calculator.sum);
System.out.println("Execution time : " + (startTime - endTime));
}
I appreciate the help!
The synchronized keyword takes the object
lock. This means that two methods that are synchronized cannot execute on the same object. They will, however, execute concurrently on invocation on 2 different objects.
In your example, your code had 8 objects of calculator. The synchronized methods do not help you. Each thread uses it's separate object. You can completely remove the synchronized keyword, and your code will be semantically equivalent.
To avoid this, use the atomic version of the objects (AtomicInt) or lock on the objects themselves: synchronized(counter){...} but for this to work you will have to change the type to Integer.
I've just tested your sample and found the addToSum method doesn't work as expected here with heavy multi-thread, even if synchronized keyword is present.
Here, as sum variable is static, the method can be made static too.
After adding the static keyword, the behavior is as expected:
private static synchronized void addToSum(int value)
{
sum += value;
}
Here a simple test (addToSum replaced by incSum for simplicity) :
class IncrementorThread implements Runnable {
private static int sum = 0;
private static synchronized void incSum()
{
sum ++;
}
public void run() {
incSum();
Thread.yield();
}
}
void testIncrementorThread1() {
ExecutorService executorService = Executors.newCachedThreadPool();
//ExecutorService executorService = Executors.newSingleThreadExecutor() // result always ok without needing concurrency precaution
for(int i = 0; i < 5000; i++)
executorService.execute(new IncrementorThread());
executorService.shutdown();
executorService.awaitTermination(4000, TimeUnit.MILLISECONDS);
System.out.println("res = "+IncrementorThread.sum); // must be 5000
}
Result must be 5000, which is not the case if we remove the static keyword from the method incSum()

Reflect changes made to a shared variable between two threads ,immediately as it is updated

these are just sample codes to ask my question the other statements are omitted
here the instance of NewClass is being passes both to Foot and Hand objects
and hence all the instances NewClass,foot and hand share the variable sno of NewClass.
public class NewClass {
volatile int sno = 100;
public static void main(String args[])
{
NewClass n = new NewClass();
Foot f = new Foot(n);
Hand h = new Hand(n);
f.start();
h.start();
}
}
public class Foot implements Runnable{
Thread t;
NewClass n;
public Foot(NewClass n)
{
this.n = n;
}
public void run(){
for(int i=0;i<100;i++)
{
System.out.println("foot thread "+ i+" "+n.sno);
n.sno=(-1)*n.sno;
Thread.sleep(1); // surrounded by try-catch
}
}
}
public class Hand implements Runnable {
Thread t;
NewClass n;
public Hand(NewClass n)
{
this.n = n;
}
public void run(){
for(int i=0;i<100;i++)
{
System.out.println("hand thread "+ i+" "+n.sno);
n.sno=(-1)*n.sno;
Thread.sleep(1); // surrounded by try -catch
}
}
}
here the sign of seq.no is changing everytime but when used by the other thread the change is many times not reflected as if the updation is taking time.so please help ,
It is not taking to long to update.
System.out.println("foot thread " + i + " " + n.sno);
n.sno=(-1)*n.sno;
When you have this happening in two threads running in parallel they may be watching the value as positive at the same time. So they both change the value to negative. If you want to control the change you need a semaphore.
In NewClass:
volatile int sno = 100;
final Object semaphore = new Object();
And in your two Runnables:
synchronized (n.semaphore) {
System.out.println("foot thread " + i + " " + n.sno);
n.sno = (-1) * n.sno;
}

some elements processed more than once, some not at all

I have a fairly straightforward task: I have a list of strings each of which is processed and a score is produced. The string and its score then get added to a map:
public class My1Thread
{
final private static List<String> ids = Arrays.asList("id1","id2","id3","id4","id5");
private static HashMap<String,Double> result = null;
private Double computeResult(String id)
{
Double res = 0.0;
// do stuff to compute result
return res;
}
public static void main(String[] args)
{
result = new HashMap<String,Double>();
for (String id: ids)
{
result.put(id,computeResult(id));
}
}
}
Since scores of any two strings are independent of each other, this seems to be a perfect case to use multithreading. However, I am getting unexpected results, which is probably a typical result for a multithreading newbie.
Here's a m/t version of the above:
public class MyMultiThread
{
final private static int nWorkers = 3; // number of threads
final private static List<String> ids = Arrays.asList("id1","id2","id3","id4","id5");
private static int curIndex = 0; // indexing pointing to position in ids currently being processed
private static HashMap<String,Double> result = null;
public static class Worker implements Runnable {
private int id;
public Worker(int id) {
this.id = id;
}
synchronized void setCounter(final int counter)
{
curIndex = counter;
}
synchronized int getCounter()
{
return curIndex;
}
synchronized void addToResult(final String id, final Double score)
{
result.put(id,score);
}
#Override
public void run()
{
try {
while (true)
{
int index = getCounter();
if (index >= ids.size())
{
// exit thread
return;
}
String id = ids.get(index);
setCounter(index+1);
System.out.print(String.format("Thread %d: processing %s from pos %d\n", id, id, curIndex-1));
Double score = ... // compute score here
addToResult(id,score);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args)
{
result = new HashMap<String,ArrayList<Pair<Document,Double>>>();
for (int i = 0; i < nWorkers; i++) {
Thread worker = new Thread(new MyMultiThread.Worker(i));
worker.start();
}
}
}
According to the output produced by System.out.print, this code appears to be processing some elements of ids more than once while not processing others at all. What am I doing wrong here?
Your while(true) loop inside the thread starts at the index specified in the constructor, and then increment it by one, and then the loop starts again. So thread 0 does index 0, then index 1, etc.. Thread 1 does index 1, then index 2, etc... So index 2 will be done 3 times.
I would use a synchronized linked list for ids, and have each thread take and remove the first element of the list, until the list is empty. Use LinkedList.removeFirst().
Also the result hash map also needs to be synchronized, since multiple threads may write to it at the same time.
The problem is that the map is being modified concurrently in multiple threads, so some updates are getting lost.
You declared the methods that modify the map as synchronized, but note that they are synchronized on multiple worker objects: not on a single object, which would provide the locking you are after.
I'd recommend using ConcurrentHashMap and getting rid of all the synchronized declarations.
Some of your synchronization is too narrow - for example, this bit here:
int index = getCounter();
if (index >= ids.size())
{
// exit thread
return;
}
String id = ids.get(index);
setCounter(index+1);
What happens if thread A reads the counter, thread B reads the counter, then thread A updates the counter?
A: int index = getCounter(); // returns 3
B: int index = getCounter(); // returns 3
...
A: setCounter(index + 1); // sets it to 4
B: setCounter(index + 1); // Uh-oh, sets it to 4 as well, we lost an update!
In this case, when you read a variable, then write to it based on the value you read, both the read and the write need to be within the same synchronization block. Declaring getCounter and setCounter as synchronized is not enough.
Simply use Java 8 Stream API :
Map<String, Double> map = ids.parallelStream().collect(Collectors.toConcurrentMap(id -> id, id -> computeScore(id)));
...
Double computeScore(String id) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return ThreadLocalRandom.current().nextDouble(100);
}
Here's a nice tutorial.

achieve atomic operation because java volatile guarantees happens-before relation?

achieve atomic operation because java volatile guarantees happens-before relation?
I have read about the happens-before for the volatile:
If Thread A writes to a volatile variable and Thread B subsequently reads the same volatilevariable, then all variables visible to Thread A before writing the volatile variable, will also be visible to Thread B after it has read the volatile variable.
Now, I have two varaibles:
static int m_x;
volatile static int m_y;
Now I have two threads, one only writes to them, and first write to m_x, and then write to m_y; The other one, only reads from them, first read m_y, and then, m_x.
My question is: is the write operation atomic? is the read operation atomic?
In my understanding, they should be atomic:
(1) On the side of writ thread, after (Write-1), it will not flush its cache to main-memory for m_x is NOT volatile, so, read-thread is not able to see the update; and after (Write-2), it will flush its cache to main-memory, for m_y is volatile;
(2) on the side of read thread, on (Read-1), it will update its cache from main memory, for m_y is volatile; and on (Read-2), it will NOT update its cache from main memory, for m_x is not volatile.
Because of the above two reason, I think the read thread should always observe the atomic value of the two variable. Right?
public class test {
static int m_x;
volatile static int m_y;
public static void main(String[] args) {
// write
new Thread() {
public
void run() {
while(true) {
int x = randInt(1, 1000000);
int y = -x;
m_x = x; // (Write-1)
m_y = y; // (Write-2)
}
}
}.start();
// read
new Thread() {
public
void run() {
while(true) {
int y = m_y; // (Read-1)
int x = m_x; // (Read-2)
int sum = y + x;
if (sum != 0) {
System.out.println("R:sum=" + sum);
System.out.println("R:x=" + x);
System.out.println("R:y=" + y);
System.out.println("\n");
}
}
}
}.start();
}
public static int randInt(int Min, int Max) {
return Min + (int)(Math.random() * ((Max - Min) + 1));
}
}
As stated in the comment, the two reads and writes are not atomic. You cannot achieve atomicity by using the volatile keyword.
This fact can be observed running your program.
To read/write both variables at the same time you either need proper synchronisation or create your own immutable value.
To do the later
public class ConcurrencyTestApp {
// use volatile for visibility
private volatile ImmutableValue immutableValue = new ImmutableValue(0, 0); // initial, non-null value
static class ImmutableValue {
private final int x;
private final int y;
ImmutableValue(final int x, final int y) {
this.x = x;
this.y = y;
}
int getX() {
return x;
}
int getY() {
return y;
}
#Override
public String toString() {
return String.format("x = %s\t| y = %s", x, y);
}
}
void replaceOldWithNewValue(final ImmutableValue newValue) {
immutableValue = newValue;
}
ImmutableValue getImmutableValue() {
return immutableValue;
}
static class Writer extends Thread {
private final ConcurrencyTestApp app;
Writer(ConcurrencyTestApp app) {
this.app = app;
}
volatile boolean isRunning = true;
#Override
public void run() {
while (isRunning) {
int x = randInt(1, 1000000);
int y = -x;
app.replaceOldWithNewValue(new ImmutableValue(x, y));
}
}
int randInt(int Min, int Max) {
return Min + (int) (Math.random() * ((Max - Min) + 1));
}
}
static class Reader extends Thread {
private final ConcurrencyTestApp app;
Reader(ConcurrencyTestApp app) {
this.app = app;
}
volatile boolean isRunning = true;
#Override
public void run() {
while (isRunning) {
ImmutableValue value = app.getImmutableValue();
System.out.println(value);
int x = value.getX();
int y = value.getY();
int sum = x + y;
if (sum != 0) {
System.out.println("R:sum=" + sum);
System.out.println("R:x=" + x);
System.out.println("R:y=" + y);
System.out.println("\n");
}
}
}
}
public static void main(String[] args) {
ConcurrencyTestApp app = new ConcurrencyTestApp();
Writer w = new Writer(app);
Reader r = new Reader(app);
w.start();
r.start();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
w.isRunning = false;
r.isRunning = false;
}
}
For further reference, I recommend the book Java concurrency in practice by Brian Goetz and Tim Peierls.
Addendum
...
Because of the above two reason, I think the read thread should always
observe the atomic value of the two variable. Right?
Wrong!
...and you are missing an important part.
For reference, see JSR 133 (Java Memory Model) FAQ by Jeremy Manson and Brian Goetz section What does volatile do?
In your program, there is nothing preventing the following:
Assume int m_x = x1 and int m_y = y1
Your Writer-Thread executes until Write-1
int m_x is now set to value x2 (which may or may not be visible to your Reader-Thread)
Your Writer-Thread's execution gets suspended (for whatever reason)
Your Reader-Thread executes Read-1 and Read-2 (there is nothing stopping the Reader-Thread from doing that)
int y = m_y which is still y1 because your Writer-Thread did not execute further yet
int x = m_x which may be x2 (but it also could still be x1)
Your Reader-Thread gets suspended and your Writer-Thread continues
int m_y is now set to value y2 (only now Read-1 would get y2 and Read-2 would be guaranteed to get x2 - unless your Writer-Thread continues)
... and so on
To see that yourself modify your writer
System.out.println("W0");
m_x = x; // non-volatile
System.out.println("W1: " + x);
m_y = y; // volatile
System.out.println("W2: " + y);
and reader thread code
System.out.println("R0");
int y = m_y; // volatile
System.out.println("R1: " + y);
int x = m_x; // non-volatile
System.out.println("R2: " + x);
So why does it not work for you?
From the reference
...volatile or not, anything that was visible to thread A when it writes to volatile field f becomes visible to thread B when it reads f.
Thus, your Reader thread is guaranteed to see the new values for m_x and m_y only when your Writer thread wrote the new value to m_y. But because no particular thread execution order is guaranteed the write operation Write-2 may not happen before Read-1 is executed.
Also see Java Volatile Keyword by Jakob Jenkov for a similar example to yours.
You assert that
"...after (Write-1), it will not flush its cache to main-memory for m_x is NOT volatile"
and
"... on (Read-2), it will NOT update its cache from main memory, for m_x is not volatile."
In fact, it is not possible to say whether or not the caches will be flushed (write), or whether or not values that are present in the cache (read). The JLS certainly does not make >>any<< guarantees for reads and writes to non-volatile variables. The guarantees apply to read and write operations on volatile variables ONLY.
While it is possible that you will observe consistent behavior for your program on certain platforms, that behavior is not guaranteed by the JLS.

Categories