Java Threads, wrong counter - java

I run below snippet and I got unexpected behaviour. Probably it is working in correct way, but I need to make it working in other way. Details below.
import java.util.ArrayList;
import java.util.List;
public class TaskExample {
public static void main(String[] args) throws InterruptedException {
final PositionHolder holder = new PositionHolder();
final List<Integer> data = new ArrayList<Integer>();
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < 20; i++) {
holder.setPosition(i);
Thread t = new Thread() {
#Override
public void run() {
data.add(holder.getPosition());
}
};
t.start();
threads.add(t);
}
for (Thread thread : threads) {
thread.join();
}
for(int i : data){
System.out.println(i);
}
}
}
class PositionHolder {
int position = 0;
public void setPosition(int position) {
this.position = position;
}
public int getPosition() {
return this.position;
}
}
And I got result:
10 12 9 8 6 6 5 4 2 1 16 16 18 19 19 19 19 19 19 19
Why? I'd like to get:
1 2 3 4 ...... 20
Is there any options to do imporve this snippet?

Try this code ;)
import java.util.ArrayList;
import java.util.List;
public class ogr
{
public static void main(String[] args) throws InterruptedException {
final PositionHolder holder = new PositionHolder();
final List<Integer> data = new ArrayList<Integer>();
for (int i = 0; i < 20; i++) {
holder.setPosition(i);
Thread t = new Thread() {
#Override
public void run() {
data.add(holder.getPosition());
}
};
t.start();
t.join();
}
for (int i : data) {
System.out.println(i);
}
}
}
class PositionHolder
{
int position = 0;
public void setPosition(int position) {
this.position = position;
}
public int getPosition() {
return this.position;
}
}

You cannot guarantee that the holder.getPosition() will get the same position values you set using holder.setPosition(i) as the getHolder call is part of a different thread and is called by multiple threads. This is because you are sharing the same PlaceHolder across all threads. If you want to get the output you desire, I would suggest using a different instance of PlaceHolder for each thread.
import java.util.ArrayList;
import java.util.List;
public class TaskExample {
public static void main(String[] args) throws InterruptedException {
final List<Integer> data = new ArrayList<Integer>();
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < 20; i++) {
// Create new instance
final PositionHolder holder = new PositionHolder(i);
Thread t = new Thread() {
#Override
public void run() {
data.add(holder.getPosition());
}
};
t.start();
threads.add(t);
for (Thread thread : threads) {
thread.join();
}
for(int i : data){
System.out.println(i);
}
}
class PositionHolder {
private int position = 0;
public PositionHolder(int position) {
this.position = position;
}
public int getPosition() {
return this.position;
}
}`

There is no way to guarantee execution order of the thread without synchronization mechanism like join() (see code proposed by Fincio).
You are getting the same number several times because you are using the same PositionHolder object for all your thread, therefore, the variable position get modified by every thread you started. Trying to do the same with an Object instead of an int would probably got you a ConcurrentAccessException. To avoid this, each thread should have its own PositionHolder instance (like in code provided by Saket). But even with that, there is no guarantee about the order in which thread will be executed.

programming using threads sometimes requires some tricks to make the threading efficient. Obviously it won't be as natural. for example check the following.
import java.util.ArrayList;
import java.util.List;
public class ogr{
public static void main(String[] args) throws InterruptedException {
ArrayList<PositionHolder> holders=new ArrayList<PositionHolder>();
final PositionHolder holder = new PositionHolder();
final List<Integer> data = new ArrayList<Integer>();
for (int i = 0; i < 20; i++) {
Thread t = new Thread() {
#Override
public void run() {
data.add(getSetPosition());
}
};
holders.add(holder)
t.start();
}
for (Thread thread : threads) {
thread.join();
}
SortByPosition(holders); //you can implement this easy by sorting arraylist by their positions
for (int i : data) {
System.out.println(i);
}
}
}
class PositionHolder{
static int staticPosition=0;
int position = 0;
public int synchronized getSetPosition() {
this.position = staticPosition++;
return position;
}
// public void setPosition(int position) {
// this.position = position;
// }
public int getPosition() {
return this.position;
}
}

Related

Not getting expected result when updating AtomicInteger variable in multiple threads

In this code I'm using 10 threads updating an AtomicInteger variable. I expect the final result of Counter.getInstance().holder.n to be 1000000, but it prints out random number like 991591.
What's wrong with my code?
public class Test {
public static void main(String[] args) {
List<Thread> list = new ArrayList<Thread>();
for (int i = 0; i < 10; i++) {
list.add(new Thread() {
public void run() {
for (int i = 0; i < 100000; i++) {
Counter.getInstance().holder.n.incrementAndGet();
}
}
});
}
for (Thread thread : list) {
thread.start();
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Counter.getInstance().holder.n);
}
}
class Counter {
private static Counter counter;
Holder holder = new Holder();
public static Counter getInstance() {
if (counter == null) {
counter = new Counter();
}
return counter;
}
class Holder {
AtomicInteger n = new AtomicInteger(0);
}
}
You have two major concurrent issues here:
You don't wait for every Thread to finish work correctly. There are multiple ways to achieve that, the simplest is to use Thread.join().
Your singleton implementation doesn't seem correct. I suppose you intended to implement it with an inner class. It seems that this answer can help to understand what's happening here.
Here is the implementation that seems more or less correct.
class Test {
public static void main(String[] args) throws InterruptedException {
List<Thread> list = new ArrayList<Thread>();
for (int i = 0; i < 10; i++) {
list.add(new Thread() {
public void run() {
for (int i = 0; i < 100000; i++) {
Counter.getInstance().n.incrementAndGet();
}
}
});
}
for (Thread thread : list) {
thread.start();
}
for (Thread thread : list) {
thread.join();
}
System.out.println(Counter.getInstance().n);
}
}
class Counter {
public AtomicInteger n = new AtomicInteger(0);
public static Counter getInstance() {
return Holder.instance;
}
private static class Holder {
private static final Counter instance = new Counter();
}
}
You can use something like CountDownLatch as well. For example:
final int count = 10;
CountDownLatch latch = new CountDownLatch(count);
List<Thread> list = new ArrayList<Thread>();
for (int i = 0; i < count; i++) {
list.add(new Thread() {
public void run() {
for (int i = 0; i < 100000; i++) {
Counter.getInstance().n.incrementAndGet();
}
latch.countDown();
}
});
}
for (Thread thread : list) {
thread.start();
}
latch.await();
System.out.println(Counter.getInstance().n);

Synchronization by this doesn't prevent concurrency [duplicate]

This question already has answers here:
Threading and synchronized methods
(3 answers)
Closed 4 years ago.
I'm very novice in multithreading in java, so would be very appreciate if someone give me brief explanation of the following:
here is my code:
public class Lesson6 {
private static volatile Long value = 0L;
public static void main(String[] args) throws InterruptedException {
Thread inc = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 100_000; i++) {
synchronized (this){
++value;
}
}
}
});
inc.start();
Thread dec = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 100_000; i++) {
synchronized (this){
--value;
}
}
}
});
dec.start();
inc.join();
dec.join();
System.out.println(value);
}
}
It seems for me, that the output should be zero, but it's never zero. Debugger shows that THIS is always different from time to time as run() methods go. Why does this happen?
Thanx.
Debugger shows that THIS is always different from time to time as run() methods go
Each new Runnable is a different object so this is different in each case.
If you use a common object, the program should work.
BTW I suggest using a primitive long for the value instead of a reference to a Long
public class Lesson6 {
private static volatile long value = 0L;
public static void main(String[] args) throws InterruptedException {
final Object locked = new Object();
Thread inc = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 100_000; i++) {
synchronized (locked){
++value;
}
}
}
});
inc.start();
Thread dec = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 100_000; i++) {
synchronized (locked){
--value;
}
}
}
});
dec.start();
inc.join();
dec.join();
System.out.println(value);
}
}
prints
0

How to consume in Producer-Consumer using Semphores?

I am trying out the Producer-Consumer problem using Semaphore. The program looks fine to me except for one place.
public class ProducerConsumerWithSemaphores
{
private final ArrayList<Integer> list = new ArrayList<>(5);
private final Semaphore semaphoreProducer = new Semaphore(1);
private final Semaphore semaphoreConsumer = new Semaphore(0);
private void produce() throws InterruptedException
{
for(int i = 0;i< 5;i++)
{
semaphoreProducer.acquire();
list.add(i);
System.out.println("Produced: " + i);
semaphoreConsumer.release();
}
}
private void consumer() throws InterruptedException
{
while (!list.isEmpty()) /// This line is where I have the doubt
{
semaphoreConsumer.acquire();
System.out.println("Consumer: " + list.remove(list.size()-1));
semaphoreProducer.release();
Thread.sleep(100);
}
}
public static void main(String[] args)
{
final ProducerConsumerWithSemaphores obj = new ProducerConsumerWithSemaphores();
new Thread(new Runnable()
{
#Override
public void run()
{
try
{
obj.produce();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable()
{
#Override
public void run()
{
try
{
obj.consumer();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}).start();
}
}
Is it okay to check the list if it is not empty before acquiring the semaphore? Will this cause any problem in multithreaded environment?
private void consumer() throws InterruptedException
{
while (!list.isEmpty()) /// This line is where I have the doubt
The problem is, if consumer runs faster than producer, your consumer quit immediately, then you have no consumer!!
The correct example looks like,
Producer–consumer problem#Using semaphores. I believe your intention is not to use true as endless loop because you want Producer/Consumer to quit when job is done. If that's your intention, you can 1. set a totalCount to end the loop. 2. Or a boolean flag which will be set by producer after putItemIntoBuffer when producer put the last one. The flag must be protected as well as the buffer.(update: this method doesn't work if there's multiple producers/consumers) 3. Simulate EOF ( idea taken from producer - consume; how does the consumer stop?)
Will this cause any problem in multithreaded environment?
Your critical section (your list) is not protected . Usually we use 3 semaphores. The 3rd one is used as a mutex to protect the buffer.
To stop producers/consumers,
Example code with method 1:
public class Test3 {
private Semaphore mutex = new Semaphore(1);
private Semaphore fillCount = new Semaphore(0);
private Semaphore emptyCount = new Semaphore(3);
private final List<Integer> list = new ArrayList<>();
class Producer implements Runnable {
private final int totalTasks;
Producer(int totalTasks) {
this.totalTasks = totalTasks;
}
#Override
public void run() {
try {
for (int i = 0; i < totalTasks; i++) {
emptyCount.acquire();
mutex.acquire();
list.add(i);
System.out.println("Produced: " + i);
mutex.release();
fillCount.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable {
private final int totalTasks;
Consumer(int totalTasks) {
this.totalTasks = totalTasks;
}
#Override
public void run() {
try {
for (int i = 0; i < totalTasks; i++) {
fillCount.acquire();
mutex.acquire();
int item = list.remove(list.size() - 1);
System.out.println("Consumed: " + item);
mutex.release();
emptyCount.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void runTest() {
int numProducer = 3;
int tasksPerProducer = 10;
int numConsumer = 6;
int tasksPerConsumer = 5;
for (int i = 0; i < numProducer; i++) {
new Thread(new Producer(tasksPerProducer)).start();
}
for (int i = 0; i < numConsumer; i++) {
new Thread(new Consumer(tasksPerConsumer)).start();
}
}
public static void main(String[] args) throws IOException {
Test3 t = new Test3();
t.runTest();
}
}
Example code with method 3:
public class Test4 {
private Semaphore mutex = new Semaphore(1);
private Semaphore fillCount = new Semaphore(0);
private Semaphore emptyCount = new Semaphore(3);
private Integer EOF = Integer.MAX_VALUE;
private final Queue<Integer> list = new LinkedList<>(); // need to put/get data in FIFO
class Producer implements Runnable {
private final int totalTasks;
Producer(int totalTasks) {
this.totalTasks = totalTasks;
}
#Override
public void run() {
try {
for (int i = 0; i < totalTasks + 1; i++) {
emptyCount.acquire();
mutex.acquire();
if (i == totalTasks) {
list.offer(EOF);
} else {
// add a valid value
list.offer(i);
System.out.println("Produced: " + i);
}
mutex.release();
fillCount.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable {
#Override
public void run() {
try {
boolean finished = false;
while (!finished) {
fillCount.acquire();
mutex.acquire();
int item = list.poll();
if (EOF.equals(item)) {
// do not consume this item because it means EOF
finished = true;
} else {
// it's a valid value, consume it.
System.out.println("Consumed: " + item);
}
mutex.release();
emptyCount.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void runTest() {
int numProducer = 3;
int tasksPerProducer = 10;
for (int i = 0; i < numProducer; i++) {
new Thread(new Producer(tasksPerProducer)).start();
}
int numConsumer = numProducer; // producers will put N EOFs to kill N consumers.
for (int i = 0; i < numConsumer; i++) {
new Thread(new Consumer()).start();
}
}
public static void main(String[] args) throws IOException {
Test4 t = new Test4();
t.runTest();
}
}
Instead of using two semaphores why dont you use a single semaphore to such that the synchronization is made between threads link
Additional you can use ArrayBlockingQueue which are thread safe to properly demonstrate the Producer Consumer Problem.

Getting error while implementing Threads

ERROR: local variable t is accessed from within inner class need to be declared final And local variable t1 is accessed from within the class.same with t1.start(); why do I need to declare them final?
public class sync {
public int count = 0;
public static void main(String args[]) {
sync obj = new sync();
obj.dowork();
sync obj1 = new sync();
obj1.dowork1();
System.out.println(count);
}
public void dowork() {
Thread t = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 1000; i++) {
count++;
}
t.start();
}
});
}
public void dowork1() {
Thread t1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 1000; i++) {
count++;
}
t1.start();
}
});
}
}
I did what you told me really helpful now it's just Showing: System.out.println("count"+count);
Identifier expected plus reach end of file while parsing
t and t1 objects are limited to scope of methods, make them member variables. Secondly, method calls and statements are called from inside a method..here t.start() & t1.start() are just floating loose inside class ... Same goes for print statement it
should also be called from inside a method.
Call to start method should be after the threads (t,t1) has been initialized. Currently they are used inside the initialization process.
It should be like this :
public void dowork(){
Thread t=new Thread (new Runnable (){
public void run(){
for (int i=0;i<1000;i++){
count++;}
}});
t.start();
}
Also count should be a static variable, as you cannot refer non-static variable from inside a static main method.
Your code be like, following think are corrected:
You make count variable static since it is been access with in static main method.
You trying to call Thread.start with in the run method which is wrong, since Thread.start method will call run method.
public class sync {
public static int count = 0;
public static void main(String args[]) {
sync obj = new sync();
obj.dowork();
sync obj1 = new sync();
obj1.dowork1();
System.out.println(count);
}
public void dowork() {
Thread t = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 1000; i++) {
count++;
}
}
});
t.start();
}
public void dowork1() {
Thread t1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 1000; i++) {
count++;
}
}
});
t1.start();
}
}
public class sync {
static int count = 0;
public static void main(String args[]) {
sync obj = new sync();
obj.dowork();
sync obj1 = new sync();
obj1.dowork1();
System.out.println(count);
}
public void dowork() {
Thread t = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 1000; i++) {
count++;
}
}
});
t.start();
}
public void dowork1() {
Thread t1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 1000; i++) {
count++;
}
}
});
t1.start();
}
}

Parallel task with synchronized arraylist

My homework was to create project using parallelization that all should be proper.
However, I made my project but my profesor mentioned something is wrong in my code "please look at array list, something is not ok, maybe synchronization?".
I would like ask you community to help me and point what could be wrong. I think it might be problem with not covering by synchronize brackets my array list, am I right?
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* My project finds all dividors for specific number
*It must use threads, so I made them. First I start them (first loop)
*then join them (second loop). My project must have that loops.
*Problem might be with not synchronizing methods array list...
*/
public class Main {
private final static int NUMBER = 100;
private final static List<Integer> dividors = new ArrayList<Integer>();
public static void main(String[] args) {
new Main().doStuff();
}
private int sqr;
private int sqrp1;
private void doStuff() {
sqr = (int) Math.sqrt(NUMBER);
sqrp1 = sqr + 1;
Thread[] t = new Thread[sqrp1];
//starting tasks
for (int i = 1; i < sqrp1; i++) {
final int it = i;
if (NUMBER % i == 0) {
final int e = i;
t[i] = new Thread(new Runnable() {
#Override
public void run() {
System.out.println("sta"+e);
if (!checkContains(e)) {
addElement(e);
}
final int dividednumber = NUMBER / e;
if (!checkContains(dividednumber)) {
addElement(dividednumber);
}
}
});
t[i].start();
}
}
//calling join for tasks
for (int i = 1; i < sqrp1; i++) {
final int it = i;
if (NUMBER % i == 0) {
try {
System.out.println("sto"+i);
t[i].join();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
System.out.println("xxx");
Collections.sort(dividors);
Integer[] arrayDividors = dividors.toArray(new Integer[0]);
for (int i = 0; i < arrayDividors.length; i++) {
System.out.println(arrayDividors[i]);
}
}
private synchronized void addElement(int element) {
dividors.add(element);
}
private synchronized boolean checkContains(int element) {
return dividors.contains(element);
}
}
Am I right changing this part, is it ok now?
t[i] = new Thread(new Runnable() {
#Override
public void run() {
System.out.println("waiting " + e);
synchronized (this) {
System.out.println("entering " + e);
if (!checkContains(e)) {
addElement(e);
}
final int dividednumber = NUMBER / e;
if (!checkContains(dividednumber)) {
addElement(dividednumber);
}
System.out.println("leaving " + e);
}
}
});
You need to turn this into a single atomic operation.
if (!checkContains(dividednumber)) {
addElement(dividednumber);
}
Imagine you have two threads.
T1: if (!checkContains(dividednumber)) { // false
T2: if (!checkContains(dividednumber)) { // false
T1: addElement(dividednumber); // adds number
T2: addElement(dividednumber); // adds same number
If you have one addElementWithoutDuplicates, this won't happen.

Categories