Write a thread safe voting system

There is a map where the key stores the name of the candidate and the value stores the number of votes obtained by the candidate. Please implement a thread safe voting system

In order to test the performance in the concurrent environment, we first design a small "framework" to simulate the voting behavior in the concurrent environment First, an interface is designed, and the code for test generation is called in the method of this interface

public interface Worker {
    void doWork();
}

And then there's the concurrent executor

public class ConcurrentRunner {

    private static   int  threadCount = 0;

    private  Worker worker;

    public void setWorker(Worker w){

        worker = w;
    }

    private ExecutorService service = Executors.newCachedThreadPool();

    ConcurrentRunner(int  count ){
        threadCount = count;
    }


    private final CountDownLatch countDownLatch = new CountDownLatch(threadCount);

    public void run(){

        for (int i = 0; i < threadCount; i++) {
            Runnable runnable = new Runnable() {
                public void run() {
                    try {
                        countDownLatch.await();

                        worker.doWork();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            service.execute(runnable);

             //When the number of threadcount threads is reached, all threads execute before
            countDownLatch.countDown();

        }
    }
}

 

Now let's get to the main topic. This topic mainly focuses on concurrency control. Of course, you can lock the whole method, but it is inefficient. It is the best solution to use CAS for reference:

import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by yzy on 2018/10/31.
 */
public class Main {

    /**
     * Number of voters
     */
    public static final int VOTER_COUNT = 100;


    /**
     * Number of candidates
     */
    public static final int CANDINATE_COUNT = 3;
    /**
     * Candidate
     * @param args
     */
    public static final String[]  candinator = {"tom","lily","jimmy"} ;

  //  private static HashMap<String , Integer> result = new HashMap(3);

    private static  ConcurrentHashMap<String , Integer> result = new ConcurrentHashMap(3);


    public static void main(String[] args) {

        ConcurrentRunner concurrentRunner = new ConcurrentRunner(VOTER_COUNT);
        concurrentRunner.setWorker(new Worker() {
            @Override
            public void doWork() {
                Random random = new Random();
                int index = random.nextInt(3);
                System.out.println("who="+index);
                String who = candinator[index];

             //   int num = result.get(who);
             //   result.put(who,1);

                result.putIfAbsent(who,0);
                int num = 0;
             //  while(!result.replace(who,num=result.get(who),num++)){
             //   while(!result.replace(who,num=result.get(who),++num)){
                while(!result.replace(who,num=result.get(who),num + 1)){

                }

            }
        });
        concurrentRunner.run();

        System.out.println("tom Votes" + result.get("tom"));
        System.out.println("lily Votes " + result.get("lily"));
        System.out.println("jimmy Votes" + result.get("jimmy"));


    }
}

Tags: Programming Java

Posted on Thu, 07 Nov 2019 07:53:32 -0800 by emopoops