Java concurrency using ConcurrentHashMap and synchronized blocks


Cheshire:

Here is my main class to initialize and start 5 different threads:

public class Server implements Runnable {
    Server1 server1;
    Thread server1Thread;

    public Server() {}

    @Override
    public void run() {
        server1 = new Server1();
        server1Thread = new Thread(server1);
        server1Thread.start();
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            Server s = new Server();
            s.run();
        }
    }
}

Here is my Server1Runnable:

import java.util.concurrent.ConcurrentHashMap;
public class Server1 implements Runnable {
    private ConcurrentHashMap<Integer, Integer> storage= new ConcurrentHashMap<>();

    public Server1() {}

    @Override
    public void run() {
        synchronized (this){
            for (int i = 0; i < 10; i++) {
                storage.put(i, (int)(Math.random()*100));
            }
            for (int i : storage.keySet()) {
                System.out.print("(" + i + "," + storage.get(i) + ") ");
            }
            System.out.println();
        }
    }
}

It ConcurrentHashMap storagestarts by putting in the key 0, 9and assigns a random value between 0and 100. After that, print it and print a new line at the end. I have the user synchronizedblock to make sure the thread itself accesses the key correctly, but it prints something like this:

(0,8) (0,87) (1,60) (1,14) (2,20) (2,70) (3,5) (0,74) (0,42) (1,22) (4,96) (0,85) (1,97) (2,75) (3,68) (4,3) (5,49) (6,3) (7,9) (8,47) (9,52) 
(3,2) (5,74) (2,86) (1,48) (3,5) (6,0) (4,0) (7,86) (4,22) (8,20) (2,17) (9,87) 
(5,96) (5,15) (6,15) (6,92) (7,48) (8,93) (9,67) 
(3,87) (7,43) (4,34) (5,48) (8,91) (9,64) 
(6,84) (7,75) (8,47) (9,87) 

Apparently this means that some thread can print out more than 10 keys that I have assigned to it. How can I make each thread print exactly the 10 keys and values ​​assigned to them and ensure concurrency here?

I'm not sure how to test.

Tom Houghton - Photo Post:

Your threads do not share any internal state. They work fine, but the output is interleaved.

For example, if you use a StringBuilderto perform I/O at a time, you should see the correct output.

        StringBuilder buff = new StringBuilder();
        for (int i : storage.keySet()) {
            buff.append("(" + i + "," + storage.get(i) + ") ");
        }
        System.out.println(buff);

There is no good reason Serverto be Runnable, not even creating any instances of it.

You do not share any maps. If you do, then you also want to share a common lock, but that's not how it's usually used ConcurrentMap.

Related


Using `synchronized` blocks with `.wait` and `.notify` in Java

Ion 20 I'm learning synchronizedcode blocks and .wait()/or methods in Java and am having a .notify()hard time understanding how they interact in a producer-consumer setup. The same instance of the class below is passed to two threads; one thread runs the produ

Synchronized methods and synchronized blocks in Java

username I'm just starting with Java synchronization and I have a small problem. is this method: public synchronized void method() { // ... do staff ... } equal: public void method() { synchronize(this) { // ... do staff ... } } polystyre

Synchronized methods and synchronized blocks in Java

username I'm just starting with Java synchronization and I have a small problem. is this method: public synchronized void method() { // ... do staff ... } equal: public void method() { synchronize(this) { // ... do staff ... } } polystyre

Java: Nested synchronized blocks

IAmYourFaja : I saw this in the version of Heinz Kabutz's Java Expert Newsletter , and while the rest (and indeed all) of Dr. Kabutz's article is well explained and detailed, he seems to gloss over what this code does, or More importantly, it means: public cla

Synchronized Blocks - Java

sky: I realize that synchronized blocks provided in Java are basically implementations of reentrant mutexes. However, are synchronized blocks atomic? So, how to handle interruption of a thread currently executing in a synchronized block - does it simply releas

Java threads and synchronized blocks

David K: Say I'm executing a block of code synchronizedinside some thread , and inside that synchronizedblock I call a method that spawns another thread to handle the synchronized block of code that requires the same lock as the first method. So, in pseudo-Jav

Java with multiple synchronized blocks

Eaton Emmerich I have some old code with many concurrency issues. The code uses sockets to connect to the server. There are multiple conditions on whether the socket is connected, this is achieved by using boolean variables (willy nilly between multiple thread

Java: Nested synchronized blocks

IAmYourFaja : I saw this in the version of Heinz Kabutz's Java Expert Newsletter , and while the rest (and indeed all) of Dr. Kabutz's article is well explained and detailed, he seems to gloss over what this code does, or More importantly, it means: public cla

Alternative to synchronized blocks in Java

Sam: I only use the following code for guaranteed startTimevariable sets: public class Processor { private Date startTime; public void doProcess() { if(startTime == null) synchronized(this) { if(st

Java threads and synchronized blocks

David K: Suppose I'm executing a block of code synchronizedinside some thread , and within that synchronizedblock I call a method that spawns another thread to handle the block of synchronized code that requires the same lock as the first method. So, in pseudo

Synchronized Blocks - Java

sky: I realize that synchronized blocks provided in Java are basically implementations of reentrant mutexes. However, are synchronized blocks atomic? So, how to handle interruption of a thread currently executing in a synchronized block - does it simply releas

Java threads: synchronized blocks

it's me I need some help making sure I understand synchronized blocks. Suppose the following example: public class ThreadStarter { public static void main(String[] args) { Queue queueObject = new Queue(); ThreadA thread1 = new ThreadA(que

Understanding Synchronized Blocks in Java

JavaUser201 I am trying to understand the concept of synchronization on objects. Using the example from the Java Cert Book, can you help me understand the difference in behavior between the following two pieces of code (one where we are synchronizing with the

Java with multiple synchronized blocks

Eaton Emmerich I have some old code with many concurrency issues. The code uses sockets to connect to the server. There are multiple conditions on whether the socket is connected, this is achieved by using boolean variables (willy nilly between multiple thread

Java with multiple synchronized blocks

Eaton Emmerich I have some old code with many concurrency issues. The code uses sockets to connect to the server. There are multiple conditions on whether the socket is connected, this is achieved by using boolean variables (willy nilly between multiple thread

Java with multiple synchronized blocks

Eaton Emmerich I have some old code with many concurrency issues. The code uses sockets to connect to the server. There are multiple conditions on whether the socket is connected, this is achieved by using boolean variables (willy nilly between multiple thread

Java with multiple synchronized blocks

Eaton Emmerich I have some old code with many concurrency issues. The code uses sockets to connect to the server. There are multiple conditions on whether the socket is connected, this is achieved by using boolean variables (willy nilly between multiple thread

Java with multiple synchronized blocks

Eaton Emmerich I have some old code with many concurrency issues. The code uses sockets to connect to the server. There are multiple conditions on whether the socket is connected, this is achieved by using boolean variables (willy nilly between multiple thread

Java with multiple synchronized blocks

Eaton Emmerich I have some old code with many concurrency issues. The code uses sockets to connect to the server. There are multiple conditions on whether the socket is connected, this is achieved by using boolean variables (willy nilly between multiple thread

Java with multiple synchronized blocks

Eaton Emmerich I have some old code with many concurrency issues. The code uses sockets to connect to the server. There are multiple conditions on whether the socket is connected, this is achieved by using boolean variables (willy nilly between multiple thread

Java threads: synchronized blocks

it's me I need some help making sure I understand synchronized blocks. Suppose the following example: public class ThreadStarter { public static void main(String[] args) { Queue queueObject = new Queue(); ThreadA thread1 = new ThreadA(que

Understanding Synchronized Blocks in Java

JavaUser201 I am trying to understand the concept of synchronization on objects. Using the example from the Java Cert Book, can you help me understand the difference in behavior between the following two pieces of code (one where we are synchronizing with the