how to demonstrate that using static variables is a tremendous error? - java

Generally, as java developers all know that we must use "synchronized" to control the method execution one by one, but I see the following code choose static variable to control, and i can't simulate the condition to demonstrate that the method is error, how do I modify the code to output the value more than 1000?
public class ThreadJunk implements Runnable{
private Info info;
public ThreadJunk(Info info) {
this.info = info;
}
public static void main(String args[]) throws Exception {
for(int j=0;j<100;j++) {
Info ii = new Info();
for(int i=0;i<1000;i++) {
Thread t = new Thread(new ThreadJunk(ii));
t.start();
}
System.out.println(ii.getValue());
}
}
#Override
public void run() {
info.addValue();
}
}
class Info {
public static boolean IS_LOCKED = false;
private int value = 0;
public void addValue() {
if(IS_LOCKED)
return;
IS_LOCKED = true;
value++;
IS_LOCKED = false;
}
public int getValue() {
return value;
}
}
In my computer, I have never get the result that more than 1000

Look at this part of your code:
Info ii = new Info();
for (int i = 0; i < 1000; i++) {
Thread t = new Thread(new ThreadJunk(ii));
t.start();
}
For every Info object you are creating no more than 1000 threads. You should not expect the value field to get incremented more than 1000 times.

Info object has value as member variable.And one Info object is shared in 999 threads as per your thread creation logic.
for(int j=0;j<100;j++) {
Info ii = new Info();
for(int i=0;i<1000;i++) {
Thread t = new Thread(new ThreadJunk(ii));
t.start();
}
System.out.println(ii.getValue());
}
Hence obviously following would be never greater than 1000.
System.out.println(ii.getValue())

Related

Consumer Producer

ProdCom.java (driver class)
import static java.lang.System.out;
public class ProdCom{
static int full = 50;
static int mutx = 0;
static int empty = 0;
static int currentSize = 0;
public static void acquire(){
while (mutx == 1);
mutx++;
}
public static void release(){
mutx--;
}
public static void main(String args[]){
Thread t = new Thread(new Producerr());
Thread t1 = new Thread(new Consumerr());
t.start();
t1.start();
}
}
Producerr.java
class Producerr implements Runnable{
public void wwait(){
while (ProdCom.currentSize >= ProdCom.full){
}
} public void signal(){
ProdCom.currentSize++;
}
public void run(){
do{
this.wwait();
ProdCom.acquire();
out.println("Num elements" + ProdCom.currentSize);
out.println("producing!");
ProdCom.release();
this.signal();
} while (true);
}
}
Consumerr.java
class Consumerr implements Runnable{
public void wwait(){
while (ProdCom.currentSize <= 0){
out.println("inside consumer wait: ");
out.println("number of elements: " + ProdCom.currentSize);
}
} public void signal(){
ProdCom.currentSize--;
}
public void run(){
do{
this.wwait();
ProdCom.acquire();
out.println("Num elements" + ProdCom.currentSize);
out.println("Consuming!");
ProdCom.release();
this.signal();
} while (true);
}
}
Above is my solution to the consumer-producer problem. The driver class ProdCom has variables full, empty and mutx for controlling producer t and consumer t1's access to the variable currentSize (Thus simulating the current number of items in a buffer). But when I run the code, the output seems to indicate t1 and t aren't taking turns to change currentSize, instead one of them repeats forever and gets stuck...I'm wondering why? Thanks.
I've improved your code a bit, and you'll notice that many of the concepts mentioned by Joni are considered.
ProdCom.java
import java.lang.*;
public class ProdCom{
static final int FULL = 50;
static final int EMPTY = 0;
static volatile int mutx = 0;
static volatile int currentSize = 0;
static Object lockObject = new Object();
public static void acquire(){
/* since mutx is defined volatile, the spinlock works,
but you reconsider this approach. There are cheaper
methods of heating the room */
while (mutx == 1);
mutx++;
}
public static boolean isEmpty() {
synchronized(lockObject) {
if (currentSize <= EMPTY) return true;
return false;
}
}
public static boolean isFull() {
synchronized(lockObject) {
if (currentSize >= FULL) return true;
return false;
}
}
public static int getCurrentSize() {
synchronized(lockObject) {
return currentSize;
}
}
public static void release(){
mutx--;
}
public static void incCurrentSize()
{
synchronized(lockObject) {
currentSize++;
}
}
public static void decCurrentSize()
{
synchronized(lockObject) {
currentSize--;
}
}
public static void main(String args[]){
Thread t = new Thread(new Producerr());
Thread t1 = new Thread(new Consumerr());
t.start();
t1.start();
}
}
Consumerr.java
import java.lang.*;
class Consumerr implements Runnable {
public void wwait() {
while (ProdCom.isEmpty()){
System.out.println("inside consumer wait: ");
System.out.println("number of elements: " + ProdCom.getCurrentSize());
try {
/* we don't spinlock here */
Thread.sleep(50);
} catch (Exception e) {
/* do nothing */
}
}
}
public void signal(){
ProdCom.decCurrentSize();
}
public void run(){
do{
this.wwait();
ProdCom.acquire();
System.out.println("Num elements " + ProdCom.getCurrentSize());
System.out.println("Consuming!");
this.signal();
ProdCom.release();
} while (true);
}
}
Producerr.java
import java.lang.*;
class Producerr implements Runnable {
public void wwait(){
while (ProdCom.isFull()){
try {
Thread.sleep(50);
} catch(Exception e) { /* do nothing */ }
}
}
public void signal(){
ProdCom.incCurrentSize();
}
public void run(){
do {
this.wwait();
ProdCom.acquire();
System.out.println("Num elements : " + ProdCom.getCurrentSize());
System.out.println("producing!");
this.signal();
ProdCom.release();
} while (true);
}
}
The Java memory models allows threads to cache the values of variables, and different threads to have different caches. This means that the spin lock in acquire easily becomes an infinite loop: the thread in acquire may use the cached value mutx = 1 and never read the updated value from main memory:
while (mutx == 1); // infinite loop even if another thread changes mutx
Another problem is that the ++ and -- operators are not atomic: they read the value of the variable, modify it, and write it back. If two threads run currentSize++ and currentSize-- at the same time it is possible one of them is lost.
You can fix these problems by using an AtomicInteger object and its methods instead of int, for example in ProdCom:
static AtomicInteger currentSize = new AtomicInteger(0);
static AtomicInteger mutx = new AtomicInteger(0);
public static void acquire() {
while (!mutx.compareAndSet(0, 1));
}
public static void release() {
mutx.set(0);
}

How do I instantiate two threads of the same object, and have the objects print different things

The goal: So I have a runnable class ThisThat. I instantiate two threads of ThisThat. One prints "This" and one prints "That". The main class is not supposed to determine what it prints.
The question: how do I make a default constructor set two different outputs for two threads of the same class? What can be improved? How can I make it only print this or that instead of both simultaneously?
Desired end result would be a program that runs for about 10 seconds and prints either this or that 10 times. Current output is "this" "that" at the same time, waits about 10 seconds and then repeats 10 times.
import java.util.Random;
public class ThisThat implements Runnable {
private String output;
private int threadNum;
public ThisThat() {
output = "";
}
public ThisThat(int t_Num) {
threadNum = t_Num;
setThisOrThat(threadNum);
}
public void setThisOrThat(int num) {
if (num == 1) {
output = "this";
} else if (num == 2) {
output = "that";
} else {
Random random = new Random();
int randNum = random.nextInt((3) + 1);
setThisOrThat(randNum);
}
}
#Override
public void run() {
for (int i=1; i <= 10; i++) {
try {
System.out.println(getOutput());
Thread.sleep((int)(800));
}
catch(InterruptedException e) {
System.err.println(e);
}
}
}
public String getOutput() { return output; }
public void setOutput(String output) { this.output = output; }
}
class Main {
public static void main(String args[]) {
Thread thread1 = new Thread(new ThisThat(1));
Thread thread2 = new Thread(new ThisThat(2));
thread1.start();
thread2.start();
}
}
One solution is to update the constructor to not take in anything from Main, then create a static volatile or Atomic property within your ThisThat class that is basically a counter changing the values for each thread instance.

Thread safe read/write to a counter

Im trying to make 2 threads that read/write to a counter using thread safe methods.
I have written some code to try test this but the read thread just reads the counter at its max (1000)
Main:
public static void main(String[] args) {
Counter c = new Counter();
Thread inc = new Increment(c);
Thread read = new Read(c);
inc.start();
read.start();
}
Counter:
public class Counter {
private int count;
public Counter() {
count = 0;
}
public synchronized void increment() {
count++;
}
public synchronized int getVal() {
return count;
}
}
Increment:
public class Increment extends Thread {
private static final int MAX = 1000;
private Counter myCounter;
public Increment(Counter c) {
myCounter = c;
}
public void run() {
for (int i = 0; i < MAX; i++) {
myCounter.increment();
}
}
}
Read:
public class Read extends Thread {
private static final int MAX = 1000;
private Counter myCounter;
public Read(Counter c) {
myCounter = c;
}
public void run() {
for (int i = 0; i < MAX; i++) {
System.out.println(myCounter.getVal());
}
}
}
Would I be better off using Atomic Integer to hold the value of the counter to allow me to safely increment it and get the value?
Your code is perfectly fine as is. It just so happened that your increment thread finished all its increments before the read thread got a chance to read. 1,000 increments takes almost no time at all.
If you want interleave execution of Read thread and Increment thread much more often then the natural operating system thread pre-emption, just make each thread give up their lock (by calling <lockedObject>.wait() followed by <lockedObject>.notify() or notifyAll() in the respective run() methods:
[In Reader]:
public void run() {
for (int i = 0; i < MAX; i++) {
synchronized (myCounter) {
System.out.println(myCounter.getVal());
try {
myCounter.wait(0L, 1);
myCounter.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
[In Increment]:
public void run() {
for (int i = 0; i < MAX; i++) {
synchronized (myCounter) {
myCounter.increment();
try {
myCounter.wait(0L, 1);
myCounter.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Upping the MAX constant to 1_000_000_000 (1 billion) made the treads interleave as well every now and then (on my machine interleave happened just by gazing at few printouts between 150 and 400_000 iterations).

Multithreading doesn't work. What is incorrect?

It's a little program written with a purpose of studying multithreading. I expected to get in main method different random numbers after run. About 4 numbers per second. But I got many thousands of zeros. Where is an error?
Main Class:
public class Main {
public static void main(String[] args) {
ExternalWorld externalWorld = new ExternalWorld();
externalWorld.start();
int x = 0;
while (true) {
while(!externalWorld.signal){
System.out.println("qqq");}
System.out.println(++x + ") " + externalWorld.getAnInt());
}
}
}
ExternalWorld Class:
import java.util.Random;
public class ExternalWorld extends Thread {
private int anInt = 0;
public boolean signal = false;
#Override
public void run() {
Random random = new Random(100);
while(true) {
anInt = random.nextInt(100);
signal = true;
try {
Thread.sleep(200);
signal = false;
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public int getAnInt() {
if (!signal) {
int p = 1 / 0;
}
int result = anInt;
anInt = 0;
return result;
}
}
problem:
private int anInt = 0;
public boolean signal = false;
You are access those variables from one thread to another thus giving you 0 and false on the main thread
solution:
use volatile keyword to access those variables from multiple threads
sample:
private volatile int anInt = 0;
public volatile boolean signal = false;

locking each item in array by java

suppose we have these classes:
public class Record {
int key;
int value;
Record(){
this.key=0;
this.value=0;
}
Record(int key,int value){
this.key=key;
this.value=value;
}
public class Table {
static final Record[] table = new Record [100];
static final Object[] locks = new Object[table.length];
static{
for(int i = 0; i < table.length; i++) {
locks[i] = new Object();
}
table[0]=new Record(0,0);
table[1]=new Record(1,10);
table[2]=new Record(2,20);
table[3]=new Record(3,30);
}
}
And i want to implement in TRansaction class these method
void setValueByID(int key, int value)
The key-value pair (record) is locked(it cannot be read/written from other transactions) until the setValueByID method finishes.
int getValueByID(int key)
The key-value pair (record) is locked until the transaction commits
void commit()
it unlocks all the key-value pairs (records) locked in the current transaction
So, my implementation is :
class Transaction extends Thread {
//there is no problem here
public void setValueByID(int key, int value){
synchronized(Table.locks[key]) {
Table.table[key].key=key;
}
}
//the problem is here...
//how can i make other thread wait until current thread calls Commit()
public int getValueByID(int key){
int value=0;
synchronized(Table.locks[key]){
value= Table.table[key].key;
}
return value;
}
void commit(){
}
Ahmad
You cannot use synchronized blocks to achieve it, instead you will need to use something like locks.
public Main {
public static void main(String[] args) {
final Transaction T = new Transaction();
for (int n = 0; n < 10; n++) {
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 1000; i++) {
T.setValueByID(i % 100, i);
T.getValueByID(i % 100);
if (i % 20 == 0) T.commit();
}
}
}).start();
}
}
}
class Table {
static final Record[] table = new Record[100];
static final ReentrantLock[] locks = new ReentrantLock[table.length];
static {
for (int i = 0; i < table.length; i++) {
locks[i] = new ReentrantLock();
}
table[0] = new Record(0, 0);
table[1] = new Record(1, 10);
table[2] = new Record(2, 20);
table[3] = new Record(3, 30);
}
}
class Transaction {
private ThreadLocal<Set<ReentrantLock>> locks = new ThreadLocal<Set<ReentrantLock>>() {
#Override
protected Set<ReentrantLock> initialValue() {
return new HashSet<ReentrantLock>();
}
};
private void attainLock(int key) {
final ReentrantLock lock = Table.locks[key];
lock.lock();
locks.get().add(lock);
}
private void releaseLock(int key) {
final ReentrantLock lock = Table.locks[key];
releaseLock(lock);
}
private void releaseLock(ReentrantLock lock) {
final Set<ReentrantLock> lockSet = locks.get();
if (!lockSet.contains(lock)) {
throw new IllegalStateException("");
}
lockSet.remove(lock);
lock.unlock();
}
private void releaseLocks() {
final Set<ReentrantLock> lockSet = new HashSet<ReentrantLock>(locks.get());
for (ReentrantLock reentrantLock : lockSet) {
releaseLock(reentrantLock);
}
}
public void setValueByID(int key, int value) {
attainLock(key);
Table.table[key].key = key;
releaseLock(key);
}
public int getValueByID(int key) {
attainLock(key);
return Table.table[key].key;
}
void commit() {
releaseLocks();
}
}
The problem with locks is that during your transaction, if you do not follow an order while attaining the locks, you can run into deadlocks! Also, you need to ensure you handle exceptions properly and always release the locks by calling commit().
This sort of synchronization is achieved using the wait()/notify() methods with some sort of lock. Read the Java tutorial on them (and other synchronization concepts) here.
Ideally you need to become familiar with the ReadWriteLock of java concurrent package. setValueId should obtain a write lock and hold it until transaction commits. getValueId only needs a read lock that can be shared by other read locks and be released when the method ends.
Also take into account some timeout so that the locks are not held indefinitely.
Research for:
read/write lock pattern
isolation levels in database systems
transaction handling

Categories

Resources