Calling synchronized from non synchronized method ISSUE [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
Why the following code does not guarantee the uniqueness of total_home number among multiple threads even when the logic is in a synchronized block.
class Country {
private static int home = 0;
int total_home;
private static synchronized int counter() {
return ++home ;
}
public void getTotal() {
total_home = counter(); System.out.println(total_home);
}
}
public class T1 extends Thread {
private Country c;
public T1(Country c) {
this.c = c;
}
#Override
public void run() {
for (int i = 0; i <= 10; i++)
c.getTotal();
}
}
public class T2 extends Thread {
private Country c;
public T2(Country c) {
this.c = c;
}
#Override
public void run() {
for (int i = 0; i <= 10; i++)
c.getTotal();
}
}
public class MainClass {
public static void main(String[] args) {
Country c = new Country();
T1 ok = new T1(c);
T2 ok1 = new T2(c);
ok.start();
ok1.start();
}
}
This is a program sample.Try to run it 5-10 times and you will see that the value of total_home is not unique every time.

Your code has:
Country c = new Country();
T1 ok = new T1(c);
T2 ok1 = new T2(c);
ok.start();
ok1.start();
Which should make it obvious: Count the amount of times new Country is executed in your code. It's.. once.
Hence, trivially, there is only one Country object available. Both you first and second thread are referring to it. (It's analogous to: They both have a unique address book. But the books contain the same address. All object variables in java are references).
Your synchronized code isn't the problem, that's working fine - every call to counter() is returning a unique value.
But, you have 2 threads all invoking getTotal() on the exact same single Country object you made.
ok.c and ok2.c are identical (they refer to the same object). Hence, they of course have the same value for total_home - there is only one total_home in the system and you overwrite it every time.
There's more in this code that indicates you need to do some more review on how java works. For example, class T1 and class T2 are entirely identical - so why do you have these?
Here's what you intended to write, I think:
public static void main(String[] args) throws Exception {
Country c1 = new Country();
Country c2 = new Country();
T1 ok1 = new T1(c1);
T1 ok2 = new T1(c2);
ok1.start();
ok2.start();
System.out.println("These are guaranteed different: " + c1.total_home + " " + t2.total_home);
}
NB: There's currently an upvoted comment that suggests that your static int home variable 'might be' cached and that you should add volatile to it. This is incorrect - synchronized is more than enough to eliminate all race conditions. However, AtomicInteger is a better option here - synchronized is a fairly 'expensive' measure, AtomicInteger gives you a guaranteed unique counter using significantly 'faster' primitives (it doesn't use locks, it uses your CPU's Compare-And-Set (CAS) infrastructure, which is orders of magnitude faster).

Related

Updating a boolean value in multithreaded process

I have the following code:
public class CheckIfSame implements Runnable {
private int[][] m;
private int[][] mNew;
private int row;
private boolean same;
public CheckIfSame(int[][] m,int[][] mNew,,int row,boolean same) {
this.m = m;
this.mNew = mNew;
this.row = row;
this.same = same;
}
#Override
public void run() {
for (int i = 0; i < mUpd[0].length; i++) {
if(m[row][i] != mUpd[row][i]) {
same = false;
}
}
}
}
Basically, the idea of this is that I use multi-threading to check row by row, whether the 2 matrices differ by at least 1 element.
I activate these threads through my main class, passing rows to an executor pool.
However, for some reason, the boolean same does not seem to update to false, even if the if condition is satisfied.
Multiple threads are trying to access that boolean at the same time: a race condition while updating the same variable.
Another possible scenario for non-volatile booleans in multithreaded applications is being affected by compiler optimizations - some threads may never notice the changes on the boolean, as the compiler should assume the value didn't change. As a result, until an specific trigger, such as a thread state change, threads may be reading stale/cached data.
You could choose an AtomicBoolean. Use it when you have multiple threads accessing a boolean variable. This will guarantee:
Synchronization.
Visibility of the updates (AtomicBoolean uses a volatile int internally).
For example:
public class CheckIfSame implements Runnable
{
//...
private AtomicBoolean same;
public CheckIfSame(..., AtomicBoolean same)
{
//...
this.same = same;
}
#Override
public void run()
{
for (int i = 0; i < mUpd[0].length; i++)
if(m[row][i] != mUpd[row][i])
same.set(false); // <--race conditions hate this
}
}

ConcurrentModificationException when trying to sum numbers of an Arraylist using multiple threads in Java

I'm new to multithreading in general, so I still don't fully understand it. I don't get why my code is having issues. I'm trying to populate an ArrayList with the first 1000 numbers, and then sum all of them using three threads.
public class Tst extends Thread {
private static int sum = 0;
private final int MOD = 3;
private final int compare;
private static final int LIMIT = 1000;
private static ArrayList<Integer> list = new ArrayList<Integer>();
public Tst(int compare){
this.compare=compare;
}
public synchronized void populate() throws InterruptedException{
for(int i=0; i<=Tst.LIMIT; i++){
if (i%this.MOD == this.compare){
list.add(i);
}
}
}
public synchronized void sum() throws InterruptedException{
for (Integer ger : list){
if (ger%MOD == this.compare){
sum+=ger;
}
}
}
#Override
public void run(){
try {
populate();
sum();
System.out.println(sum);
} catch (InterruptedException ex) {
Logger.getLogger(Tst.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
Tst tst1 = new Tst(0);
tst1.start();
Tst tst2 = new Tst(1);
tst2.start();
Tst tst3 = new Tst(2);
tst3.start();
}
}
I expected it to print "500.500‬", but instead it prints this:
162241
328741
Exception in thread "Thread-0" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1042)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:996)
at tst.Tst.sum(Tst.java:38)
at tst.Tst.run(Tst.java:50)
BUILD SUCCESSFUL (total time: 2 seconds)
The problem is happening because your methods are synchronized in "object level", I mean, the monitor lock it uses is of a particular object (tst1,tst2,tst3). In other words, each synchronized method is using a different lock.
Change your synchronized methods to static as a first step to fix it.
while run of tst1 is counting the sum in for-each then run of tst2 might increasing the size of list. So its throwing concurrent modification exception. Using a join can help.
public static void main(String[] args) {
Tst tst1 = new Tst(0);
tst1.start();
tst1.join()
Tst tst2 = new Tst(1);
tst2.start();
tst1.join()
Tst tst3 = new Tst(2);
tst3.start();
}
You misunderstood the semantic of synchronized method, each one uses different lock object in your case, do it this way:
class SynchList {
private int sum = 0;
private final int MOD = 3;
private int compare;
private final int LIMIT = 1000;
private ArrayList<Integer> list = new ArrayList<Integer>();
public synchronized void populate( int compare) throws InterruptedException{
for(int i=0; i<=LIMIT; i++){
if (i%this.MOD == compare){
list.add(i);
}
}
}
public synchronized void sum( int compare ) throws InterruptedException{
for (Integer ger : list){
if (ger%MOD == compare){
sum+=ger;
}
System.out.println( sum );
}
}
}
class Tst extends Thread {
int compare;
SynchList synchList;
public Tst(int compare, SynchList synchList)
{
this.compare= compare;
this.synchList = synchList;
}
#Override
public void run(){
try {
synchList.populate( compare );
synchList.sum( compare );
} catch (InterruptedException ex) {
Logger.getLogger(Tst.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class Main
{
public static void main(String[] args) {
SynchList synchList = new SynchList();
Tst tst1 = new Tst( 0 , synchList );
tst1.start();
Tst tst2 = new Tst( 1, synchList );
tst2.start();
Tst tst3 = new Tst( 2, synchList );
tst3.start();
}
}
Your use of synchronized methods isn't doing what you think it's doing. The way your code is written, the methods "sum" and "populate" are protected
from running at the same time, but only on the same thread instance. That means calls to "sum" and "populate" for a single Tst object will happen one at a time,
but simultaneous calls to "sum" on different object instances will be allowed to happen concurrently.
Using synchronized on a method is equivalent to writing a method that is wrapped
with synchronized(this) { ... } around the entire method body. With three different instances created – tst1, tst2, and tst3 – this form of synchronization
doesn't guard across object instances. Instead, it guarantees that only one of populate or sum will be running at a time on a single object; any other calls to one of
those methods (on the same object instance) will wait until the prior one finishes.
Take a look at 8.4.3.6. synchronized Methods in the Java Language Specification
for more detail.
Your use of static might also not be doing what you think it's doing. Your code also shares things across all instances of the Tst thread class – namely, sum and list. Because these are defined as static,
there will be a one sum and one list. There is no thread safety in your code to guard against concurrent changes to either of those.
For example, as threads are updating
"sum" (with the line: sum+=ger), the results will be non-deterministic. That is, you will likely see different results every time you run it.
Another example of unexpected behavior with multiple threads and a single static variable is list – that will grow over time which can result in concurrency issues. The Javadoc says:
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.
Modifications include adding values as well as growing the backing array store. Without specifying a starting size – new ArrayList() – it will default to 10 or possibly some other relatively small number depending on which JVM version you're using. Once one thread tries to add an item that exceeds the ArrayList's capacity, it will trigger an automatic resize.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

Synced multithreading add 1 to number, varying results

I don't know if this is working the right way, but I'm attempting to add 1 to a variable using 1000 threads. I then print out the number at the end to verify that it worked, it never is 1000 and it also changes.
I determined this is likely a synchronization issue from googling and look on SO but when I try to sync the threads, it still isn't 1000 at the end and varies but a lot less (varies between 995 to 997 whereas without sync it varies between 900 and 1000 roughly).
Here is what I'm doing so far:
public class Main extends Thread{
public static void main(String[] args) {
Thread[] threads = new Thread[1000];
Adder adder = new Adder();
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new ThreadAddSync(adder));
threads[i].start();
}
System.out.println("----- " + adder.count);
}
}
public class ThreadAddSync implements Runnable{
Adder add;
public ThreadAddSync(Adder add){
this.add = add;
}
#Override
public void run() {
synchronized(add){
add.add();
}
}
}
public class Adder {
int count = 0;
public void add(){
count += 1;
}
}
My question is should these threads be synced the way I have this written? And if they are synced why are they producing varying results if they're technically safe?
System.out.println("----- " + adder.count); - you access count but don't synchronize on adder and thus, it is not safe (nor did you wait for the workers to complete, join() if you expect to see the final total before you print the total, or add another loop to wait). Also, in real code, you should be using AtomicInteger.

Sharing variable between threads in JAVA

I have two threads doing calculation on a common variable "n", one thread increase "n" each time, another decrease "n" each time, when I am not using volatile keyword on this variable, something I cannot understand happens, sb there please help explain, the snippet is like follow:
public class TwoThreads {
private static int n = 0;
private static int called = 0;
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
n = 0;
called = 0;
TwoThreads two = new TwoThreads();
Inc inc = two.new Inc();
Dec dec = two.new Dec();
Thread t = new Thread(inc);
t.start();
t = new Thread(dec);
t.start();
while (called != 2) {
//System.out.println("----");
}
System.out.println(n);
}
}
private synchronized void inc() {
n++;
called++;
}
private synchronized void dec() {
n--;
called++;
}
class Inc implements Runnable {
#Override
public void run() {
inc();
}
}
class Dec implements Runnable {
#Override
public void run() {
dec();
}
}
}
1) What I am expecting is "n=0,called=2" after execution, but chances are the main thread can be blocked in the while loop;
2) But when I uncomment this line, the program when as expected:
//System.out.println("----");
3) I know I should use "volatile" on "called", but I cannot explain why the above happens;
4) "called" is "read and load" in working memory of specific thread, but why it's not "store and write" back into main thread after "long" while loop, if it's not, why a simple "print" line can make such a difference
You have synchronized writing of data (in inc and dec), but not reading of data (in main). BOTH should be synchronized to get predictable effects. Otherwise, chances are that main never "sees" the changes done by inc and dec.
You don't know where exactly called++ will be executed, your main thread will continue to born new threads which will make mutual exclusion, I mean only one thread can make called++ in each time because methods are synchronized, and you don't know each exactly thread will be it. May be two times will performed n++ or n--, you don't know this, may be ten times will performed n++ while main thread reach your condition.
and try to read about data race
while (called != 2) {
//System.out.println("----");
}
//.. place for data race, n can be changed
System.out.println(n);
You need to synchronize access to called here:
while (called != 2) {
//System.out.println("----");
}
I sugest to add getCalled method
private synchronized int getCalled() {
return called;
}
and replace called != 2 with getCalled() != 2
If you interested in why this problem occure you can read about visibility in context of java memory model.

how can I get array values back from a thread

I have a thread, in Java, putting the first 100 Fibonacci numbers in an array. How do I get the numbers back from the thread. Is there an interrupt, handling, exception, implements, extends? I have been adding things and the trial and error is not getting me anywhere to understanding.
import java.util.Scanner;
import java.io.*;
import java.lang.Thread; //don't know if this is needed
public class FibThread extends Thread{
public FibThread (){
super();
}
public void run(int inputNum){
System.out.println(inputNum);
long[] fibArray = new long[inputNum];
fibArray[0]=0;
fibArray[1]=1;
fibArray[2]=1;
for(int i = 3; i<inputNum; i++){
fibArray[i]= fibArray[i-1] + fibArray[i-2];
// }
//System.out.println( );
// for(int j = 0; j<= inputNum; j++){
int output = (int) fibArray[i];
System.out.println(output);
}
}
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
FibThread threadOne;
int inputNum, itter, output;
System.out.println("Please enter the number of Fibonacci numbers to be generated: ");
itter = keyboard.nextInt();
//inputNum = itter;
threadOne = new FibThread();
threadOne.start();
// for(int j = 0; j<= inputNum; j++){
// int output = (int) fibArray[j];
// System.out.println(output);
}
}
If you have a "task" that returns a value, make it a Callable.
If you want the callable to run in a background thread, then instead of handling the creation and execution of threads yourself, it's generally better to abstract this through an ExecutorService. A caller can interact with the service by passing in a Callable, and getting back a Future that will be populated with the value when the calculation has completed.
To modify your example, renaming FibThread to FibCalc:
public class FibCalc implements Callable<Integer> {
// We need some way to pass in the initial input - must be through the
// constructor and we'll store it here
private final inputNum;
public FibCalc(int inputNum) {
this.inputNum = inputNum;
}
public int call() {
// The same as your run() method from before, except at the end:
...
return output;
}
}
// And now for your main() method
public static void main(String[] args) throws Exception {
// As before up to:
...
itter = keyboard.nextInt();
// Create a very simple executor that just runs everything in a single separate thread
ExecutorService exec = Executors.newSingleThreadExecutor();
// Create the calculation to be run (passing the input through the constructor)
FibCalc calc = new FibCalc(itter);
// Send this to the executor service, which will start running it in a background thread
// while giving us back the Future that will hold the result
Future<Integer> fibResult = exec.submit(fibCalc);
// Get the result - this will block until it's available
int result = fibResult.get();
// Now we can do whatever we want with the result
System.out.println("We got: " + result);
}
If you absolutely have to create a Thread object yourself (due to artificial constraints on a homework question, or something like that - I can't see why one would realistically do this in reality), then the approach has to be different. You can't return a value because run() must return void due to the interface. So my approach here would be to store the result in a local variable of the FibThread class, and then add a method to that class (e.g. public int getResult()) which returned that variable.
(If you're doing it this way, bear in mind that you'll have to handle the concurrency issues (i.e. letting the caller know the result is ready) yourself. A naive approach, where the main method starts the thread and then immediately calls getResult(), means that it will almost certainly get an "empty" result before the calculation has finished. A crude solution to this problem would be calling join() on the spawned thread, to wait for it to finish before accessing the result.)

Categories