need a simple example for the synchronization - java

public class Test implements Runnable{
private String name;
public Test(String name){
this.name = name;
}
public void run() {
blah(name);
}
public synchronized void blah(String obj) {
System.out.println("Here: "+obj);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test x = new Test("X");
Test y = new Test("Y");
Thread tx = new Thread(x);
Thread ty = new Thread(y);
tx.start();
ty.start();
}
This example should help me to understand synchronization, but I don't. This is because if I remove the word synchronize, it printed the same output (random)

Synchronization is irrelevant here because your two threads are each synchronizing on their own Runnable. There is no shared lock, and no shared data.
If you pass the same Runnable instance into each Thread then they will share the same lock. If your Runnable does something in a thread-unsafe way (like using ++ to increment a shared variable (an instance variable of the Runnable), or adding the entry to a shared ArrayList) then you can create a situation where removing synchronization can make the code break (with the understanding that breakage may not happen reliably, that's what makes multithreaded programming fun).
Making toy examples like this is not a good preparation for real-life multithreading. Threads shouldn't be in the business of implementing locking, they should be accessing data objects that enforce their own invariants.

Your example is technically correct, but there is no timing dependent conflict in your synchronized block. As such, there is no chance that you will see different output, regardless of the ordering of the calls.
In addition, you create two resources, and there is no cross-thread communication between the two resources, so effectively you've tested two synchronized blocks once each.
You need an example that can break when not synchronized.
Here is an example that can break
public class Counter {
int count;
public Counter() {
count = 0;
}
public int getCount() {
return count;
}
public /* need synchronized here */ void update(int value) {
int buffer = 0;
buffer = buffer + count;
buffer = buffer + value;
count = buffer;
}
}
public class UpdateCounter extends Thread {
public UpdateCounter(Counter counter, int amount) {
this.counter = counter;
this.name = name;
}
public void run() {
System.out.printf("Adding %d to count\n", amount);
counter.update(amount);
System.out.printf("Count is %d\n", counter.getCount());
}
}
public static void main(String[] args) {
Counter counter = new Counter();
UpdateCounter x = new UpdateCounter(counter, 30);
UpdateCounter y = new UpdateCounter(counter, 100);
x.start();
y.start();
}
With an example like this, one would eventually see a series of lines that indicated some value was being added to the counter, but the counter would update by the wrong value.
This is because one thread will eventually get paused with a buffer holding the "next" value, and the other thread will race across the same block of code, storing its "next" value into count. Then the paused thread will un-pause, and store its "next" value effectively removing the amount added by the thread that raced ahead of it.
By adding the synchronized keyword, only one thread is allowed entry into the update block, and the race condition I described above cannot occur.
Note that this is an example that can fail with bad synchronization, and not a good way to implement a counter.

Related

What is the correct way to avoid an empty synchronized block?

Recently I've started looking into multithreading, and I have a question, perhaps more experienced ones could help.
My program creates two parallel threads, each of them prints counts from 0 to 19 (the NumbersPrinter class, which implements the Runnable interface).
class NumbersPrinter implements Runnable {
private Mediator mediator;
private String name;
private int makeActionOnCount;
public NumbersPrinter(Mediator mediator, String name, int makeActionOnCount) {
this.mediator = mediator;
this.name = name;
this.makeActionOnCount = makeActionOnCount;
}
#Override
public void run() {
for(int i = 0; i<20; i++){
try {
synchronized(this.mediator) {
if(this.mediator.actionInProgress.get()) {
System.out.println(name + " waits");
wait();
}
}
System.out.println(this.name + " says " + i);
Thread.sleep(500);
if(i == makeActionOnCount) {
synchronized(this.mediator) {
System.out.println(this.name + " asks Mediator to perform action...");
this.mediator.performAction();
this.mediator.notify();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
When one of the threads reaches a certain number (defined in the makeActionOnCount variable), it starts performing a certain action that stops the execution of the second counter. The action lasts 5 seconds and after that both counters continue to count.
The counters are interconnected through an instance of the Mediator class, the performAcyion() method also belongs to the instance of the Mediator class.
import java.util.concurrent.atomic.AtomicBoolean;
class Mediator {
public AtomicBoolean actionInProgress = new AtomicBoolean(false);
public Mediator() {
}
public void performAction() throws InterruptedException {
actionInProgress.set(true);
System.out.println("Action is being performed");
Thread.sleep(5000);
System.out.println("Action has been performed");
actionInProgress.set(false);
}
}
Here's the Main class:
class Main {
public static void main(String[] args) throws InterruptedException{
Mediator mediator = new Mediator();
NumbersPrinter data = new NumbersPrinter(mediator, "Data", 10);
NumbersPrinter lore = new NumbersPrinter(mediator, "Lore", 5);
Thread oneThread = new Thread(data);
Thread twoThread = new Thread(lore);
System.out.println("Program started");
oneThread.start();
twoThread.start();
oneThread.join();
twoThread.join();
System.out.println("Program ended");
}
The way the program is written now - works fine, but I don't quite understand what exactly should I write in the first synchronized block, because if you delete all content from it, the program still works, since the counter that does not execute the performAction() method stops 'cause the counter cannot access the monitor of the Mediator object 'cause it is busy with the parallel counter. AtomicBoolean variable and checking it also makes no sense.
In other words, I may not use the wait () and notify () constructs at all, as well as the value of the AtomicBoolean variable, and just check access to the Mediator object's monitor every new iteration using an empty synchronized block. But I've heard that an empty synchronized block is a bad practice.
I am asking for help on how to rewrite the program to use the synchronized block and the wait() and notify() methods correctly.
Maybe I'm syncing on the wrong object? How would you solve a similar problem?
Thanks in advance

Java - Synchronized but allow one method to be accessed by different threads

In the example below:
public class MsLunch {
private long c1 = 0;
private long c2 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();
public void inc1() {
synchronized(lock1) {
c1++;
}
}
public void inc2() {
synchronized(lock2) {
c2++;
}
}
}
inc1 and inc2 can be accessed at the same time, but neither can be accessed by multiple threads at the same time.
How would it be possible to allow only inc1 or inc2 to be accessed whilst the other is like regular syncing however allowing the one that is being accessed to be done so by as many threads as possible.
I think a useful analogy is traffic passing through an intersection, where you can have multiple cars sharing one road, as long as they're driving in parallel. The challenge is finding a coordination strategy for intersecting traffic.
The solution proposed by #Greg works if traffic is intermittent and we can wait for one stream to stop before allowing the intersecting stream to proceed. But I suspect that's not very realistic. If there's steady traffic on one road, the rest of the cars will wait forever, a.k.a. thread starvation.
An alternative strategy is to allow cars to cross on a first come, first served basis, like at a stop sign. We can implement that using a dedicated semaphore for each "road", or segment, where each user takes a permit, after first making sure none of the other segments have permits in use:
public class StopSign {
private final Semaphore[] locks;
private volatile int current = 0;
public StopSign(int segments) {
// create and populate lock array, leaving
// all segments drained besides the first
locks = new Semaphore[segments];
Arrays.setAll(locks, i -> new Semaphore(i == 0 ? Integer.MAX_VALUE : 0, true));
}
public void enter(int segment) {
// synchronization is necessary to guard `current`,
// with the added benefit of holding up new threads
// in the active segment while we're gathering permits
synchronized (locks) {
if (segment == current) {
// if our segment is active, acquire a permit
locks[segment].acquireUninterruptibly();
} else {
// otherwise, gather all permits from the active segment
// as they become available and then reclaim our own permits
locks[current].acquireUninterruptibly(Integer.MAX_VALUE);
current = segment;
locks[segment].release(Integer.MAX_VALUE - 1);
}
}
}
public void exit(int segment) {
if (segment != current) {
// we don't own the lock!
throw new IllegalMonitorStateException();
}
locks[segment].release();
}
}
To use the class, we simply call enter(i) and exit(i), where i identifies the road/segment/method we want to use. Here's a demo using 3 segments:
public static void main(String args[]) {
int segments = 3;
StopSign lock = new StopSign(segments);
IntStream.range(0, segments).parallel().forEach(i -> {
for (int j = 0; j < 10; j++) {
lock.enter(i);
System.out.print(i);
lock.exit(i);
sleepUninterruptibly(20, TimeUnit.MILLISECONDS);
}
});
}
A test run on my machine produces this alternating pattern:
120201210012012210102120021021
This strategy could make sense if traffic is relatively light, but in heavy traffic the overhead of coordinating each crossing can significantly restrict throughput. For busy intersections, you'll usually want a traffic light, or a third party that can transfer control at a reasonable frequency. Here's an implementation of a such a concept, using a background thread that manages a set of read/write locks, making sure only one segment has a write lock available at a time:
public class TrafficLight {
private final ReadWriteLock[] locks;
private final Thread changer;
public TrafficLight(int segments, long changeFrequency, TimeUnit unit) {
// create and populate lock array
locks = new ReadWriteLock[segments];
Arrays.setAll(locks, i -> new ReentrantReadWriteLock(true));
CountDownLatch initialized = new CountDownLatch(1);
changer = new Thread(() -> {
// lock every segment besides the first
for (int i = 1; i < locks.length; i++) {
locks[i].writeLock().lock();
}
initialized.countDown();
int current = 0;
try {
while (true) {
unit.sleep(changeFrequency);
// lock the current segment and cycle to the next
locks[current].writeLock().lock();
current = (current + 1) % locks.length;
locks[current].writeLock().unlock();
}
} catch (InterruptedException e) {}
});
changer.setDaemon(true);
changer.start();
// wait for the locks to be initialized
awaitUninterruptibly(initialized);
}
public void enter(int segment) {
locks[segment].readLock().lock();
}
public void exit(int segment) {
locks[segment].readLock().unlock();
}
public void shutdown() {
changer.interrupt();
}
}
Now let's tweak the test code:
TrafficLight lock = new TrafficLight(segments, 100, TimeUnit.MILLISECONDS);
The result is an orderly pattern:
000111112222200000111112222200
Notes:
awaitUninterruptibly() and sleepUninterruptibly() are Guava helper methods to avoid handling InterruptedException. Feel free to copy the implementation if you don't want to import the library.
TrafficLight could be implemented by delegating state management to visiting threads, instead of relying on a background thread. This implementation is simpler (I think), but it does have some extra overhead and it requires a shutdown() to be garbage collected.
The test code uses parallel streams for convenience, but depending on your environment, it may not interleave very well. You can always use proper threads instead.
You could keep track of what mode you're in, and how many operations of that type are in progress, then only flip the mode when all of those operations are complete, eg:
public class MsLunch {
private enum LockMode {IDLE, C1_ACTIVE, C2_ACTIVE};
private LockMode lockMode = IDLE:
private int activeThreads = 0;
private long c1 = 0;
private long c2 = 0;
public void inc1() {
try {
enterMode(C1_ACTIVE);
c1++
} finally {
exitMode();
}
}
public void inc2() {
try {
enterMode(C2_ACTIVE);
c2++
} finally {
exitMode();
}
}
private synchronized void enterMode(LockMode newMode){
while(mode != IDLE && mode != newMode) {
try {
this.wait(); // don't continue while threads are busy in the other mode
} catch(InterruptedException e) {}
}
mode = newMode;
activeThreads++;
}
private synchronized void exitMode(){
activeThreads--;
if (activeThreads == 0) {
mode = IDLE;
this.notifyAll(); // no more threads in this mode, wake up anything waiting
}
}
}

Loop in multiple Threads

right now i'm trying to get my head arround threads and concurrency,
so i tried to make multiple threads which counts together to 1000.
Example: Thread 1=0, Thread 2=1.Thread 3=2, and so on
As you will see in the code i implemented the Runnable interface and started the threads.
What i can see is that every thread starts the loop only for itself even if i use a synchronized method.
This is the loop "class"
private String threadname;
private int counter;
Task3(String threadname,int counter) {
this.threadname = threadname;
this.counter =counter;
}
private synchronized void compute(int i) {
try {
// "simulate" computation
System.out.println(threadname);
Thread.sleep(100);
System.out.println(" " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
for(int i=0; i <= counter;i++)
compute(i);
}
and in this class i start 4 threads with a for loop and give the method aboce the parameters which is only the thread name and how often they should count...
for(int i=0; i<=3;i++){
Runnable r =new Thread(new Task3("Thread"+i,1000));
Thread t = new Thread(r);
t.start();
}
thanks in advance
Explanation
Synchronized only means that it is ensured that a thread waits before entering the method until another thread has finished executing this method. This means that only one thread, at one time, can be inside of this synchronized method.
This can prevent strange behavior when using non-atomic operations. For example threads catching outdated values, thinking they would be up-to-date.
Solution
If you want that all threads count together you need some kind of shared resource, i.e. the counter. Currently every thread has his own counter. You need one counter in total which is shared among all threads.
A quick and dirty method would be to make the counter static. But you can probably do better with a design like this:
Class which manages the threads:
public class Demo {
public static void main(String[] args) {
Demo demo = new Demo();
for (int i = 0; i < 3; i++) {
Counter counter = new Counter(demo, 1000);
counter.start();
}
}
// Provide a shared resource for all threads
private int sharedCounter = 0;
// Provide a count method for all threads
// which is synchronized to ensure that no
// strange behavior with non-atomic operations occurs
public synchronized void count() {
sharedCounter++;
}
}
And the Thread class:
public class Counter extends Thread {
private Demo mDemo;
private int mAmount;
public Counter(Demo demo, int amount) {
// Remember the shared resource
mDemo = demo;
mAmount = amount;
}
#Override
public void run() {
for (int i < 0; i < mAmount; i++) {
// Call the count method provided
// by the shared resource
mDemo.count();
// Sleep some millis
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Identifying the threads accessing a static block of code?

I have a static function like:
public static void foo()
{
//code follows
System.out.println(Thread.currentThread().getName());
//code follows
}
and multiple threads are calling this function concurrently. I have set the names of threads using
Thread.setName(String)
When i execute the code, the print statement will print the name of only one thread. How can i identify the names of all the threads currently executing the foo() function?
EDIT:
public class FooThread extends Thread
{
public FooThread(String name)
{
this.setName(name);
}
#Override public void run()
{
//do something
//do something
Main.foo();
}
}
//Main Class
public class Main
{
public static void main(String[] args)
{
for(int i=0;i<6;++i)
{
new FooThread("Thread"+i).start();
}
}
public static void foo()
{
//do something
while(true)
{
//do something
System.out.println(Thread.currentThread().getName());
}
}
}
You're already showing the name of the Thread that is calling your code. Code that proves this:
public class Foo2 {
public static synchronized void foo() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
int maxCount = 10;
for (int i = 0; i < maxCount; i++) {
Thread thread = new Thread(new Runnable() {
public void run() {
foo();
}
});
thread.setName("Thread " + i);
thread.start();
long sleepTime = 1000;;
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {}
}
}
}
Return:
Thread 0
Thread 1
Thread 2
Thread 3
Thread 4
Thread 5
Thread 6
Thread 7
Thread 8
Thread 9
Your problem lies in code not shown.
Either your method is being called by one and only one thread, or
Or you're giving all your threads the same name.
Again, for a complete solution as to what is actually wrong with your current set up, create and post an sscce similar to what I've posted above. For all we know you could be calling run() on your Threads, and until we can see and reproduce your problem, I don't think that we'll be able to fully understand it.
EDIT
Regarding your SSCCE: Compare the results of the two methods below, foo1() and foo2()
class FooThread extends Thread {
public FooThread(String name) {
this.setName(name);
}
#Override
public void run() {
// do something
// do something
Main.foo1(); // !! Swap comments
// Main.foo2(); // !! Swap comments
}
}
// Main Class
public class Main {
private static final long SLEEP_TIME = 4;
public static void main(String[] args) {
for (int i = 0; i < 6; ++i) {
new FooThread("Thread" + i).start();
}
}
public static void foo1() {
// do something
while (true) {
// do something
synchronized (Main.class) {
System.out.println(Thread.currentThread().getName());
}
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {}
}
}
public static void foo2() {
while (true) {
System.out.println(Thread.currentThread().getName());
}
}
}
If your while loop isn't so tight, but yields the CPU with say a short Thread.sleep, you'll see more of the different threads sharing foo in closer proximity.
But again, your code also proves that your Thread names *are8 being displayed, but that you're only seeing one name likely because that thread is hogging the CPU.
Another option is to get all the Thread stacks and look for all the threads in the foo() This has the benefit of no overhead or extra code, except to capture the information you want.
BTW: Can you make it clearer why do you need this information as I suspect there is a better way to do what you really want?
If you only want to get the count of threads, use a thread-safe counter to store number of threads. Increase the counter when foo() begins, and decrease the counter when foo() exits.
If you need to get the names, use a hash set (or list if there are duplicates of thread names) to store the names: Add the name when foo() begins, and remove the name when foo() exits. Make sure the access to hash set is thread safe. You also need another method to print out the content of the hash set, so you can call it any time to see what are the name of threads executing foo().
You can put the name into a list when the method starts (in a synchronized block) and remove it at the end again.
List allTheNames = Collections.synchronizedList(new ArrayList<String>());
public void foo() {
allTheNames.add(Thread.currentThread().getName());
// now allTheNames contains all the names of all threads currently in this method.
System.out.println(allTheNames.toString());
allTheNames.remove(Thread.currentThread().getName());
}
Of course, if you change the name of the thread in the meantime that wont work, but why would you do so?
You could also store the Thread itself if you need other informations that the name.

Uses of volatile without synchronization

Knowing that
Reads and writes are atomic for all variables declared volatile
Question1: Can this be understood as if
private volatile int x = 0;
x++; operation is atomic?
And that
Marking variable volatile does not eliminate all need to synchronize
atomic actions, because memory consistency errors are still possible.
Question2: I wonder under what circumstances (if any) it is possible to see a variable marked volatile and not see any methods of blocks marked synchronized (that attempt to access/ modify the variable)?
In other words, should all variables that need to be protected from concurrent modification be marked volatile?
The volatile only gives you additional visibility guarantees, atomic writes/reads for longs/doubles (otherwise not guaranteed by the JLS, yes) and some memory order guarantees. No synchronization (it is possible though to build synchronization blocks starting with just volatile - Dekker's algorithm )
So no, it does not help you with x++ - that's still a read, inc and write and needs some form of synchronization.
One example of volatile is the famous double-checked locking, where we avoid synchronization most of the time because the ordering guarantees are all we need:
private volatile Helper helper = null;
public Helper getHelper() {
if (helper == null) {
synchronized(this) {
if (helper == null) {
helper = new Helper();
}
}
}
return helper;
}
An example where there's absolutely no synchronization involved, is a simple exit flag, here it's not about ordering guarantees but only about the guaranteed visibility
public volatile boolean exit = false;
public void run() {
while (!exit) doStuff();
// exit when exit set to true
}
If another thread sets exit = true the other thread doing the while loop is guaranteed to see the update - without volatile it may not.
x++; operation is atomic?
No. This reduces to x = x + 1. The read of x is atomic, and the write to x is atomic, but x = x + 1 as a whole is not atomic.
I wonder under what circumstances (if any) it is possible to see a variable marked volatile and not see any methods of blocks marked synchronized (that attempt to access/ modify the variable)?
Well, there are all kinds of approaches to concurrency that don't use synchronized. There's a wide variety of other locking utilities in Java, and lock-free algorithms that still require things like volatile: ConcurrentLinkedQueue is a specific example, though it makes extensive use of "magical" compareAndSet atomics.
As a quickly testable example that may illustrate the previous answers, this yields always a final count of 8:
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadTest_synchronize {
public static void main(String[] args) {
ThreadTest_synchronize tt = new ThreadTest_synchronize ();
try {
tt.go();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void go() throws InterruptedException{
MyRunnable t = new MyRunnable();
Thread myThread_1 = new Thread( t, "t1");
Thread myThread_2 = new Thread( t, "t2");
myThread_1.start();
myThread_2.start();
myThread_1.join();
myThread_2.join();
System.out.println("Processing count="+t.getCount());
}
private class MyRunnable implements Runnable{
private AtomicInteger count=new AtomicInteger(0);
#Override
public void run() {
for(int i=1; i< 5; i++){
doSomething(i);
count.getAndAdd(1);
}
}
public AtomicInteger getCount() {
return this.count;
}
private void doSomething(int i) {
try {
Thread.sleep(i*300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
while this generally does not:
public class ThreadTest_volatile {
public static void main(String[] args) {
ThreadTest_volatile tt = new ThreadTest_volatile ();
try {
tt.go();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void go() throws InterruptedException{
MyRunnable t = new MyRunnable();
Thread myThread_1 = new Thread( t, "t1");
Thread myThread_2 = new Thread( t, "t2");
myThread_1.start();
myThread_2.start();
myThread_1.join();
myThread_2.join();
System.out.println("Processing count="+t.getCount());
}
private class MyRunnable implements Runnable{
private volatile int count = 0;
#Override
public void run() {
for(int i=1; i< 5; i++){
doSomething(i);
count++;
}
}
private int add(int count){
return ++count;
}
public int getCount(){
return count;
}
private void doSomething(int i) {
try {
Thread.sleep(i*300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Categories