Creare un file denominato dizionario.txt con i seguenti contenuti:
a
as
an
b
bat
ball
Qui abbiamo: conte di parole che iniziano con "a": 3
Conte di parole che iniziano con "b": 3
parola totale contare: 6
Ora eseguire il seguente programma come: java WordCount test_dictionary.txt 10
public class WordCount {
String fileName;
public WordCount(String fileName) {
this.fileName = fileName;
}
public void process() throws Exception {
long start = Instant.now().toEpochMilli();
LongAdder totalWords = new LongAdder();
//Map<Character, LongAdder> wordCounts = Collections.synchronizedMap(new HashMap<Character, LongAdder>());
ConcurrentHashMap<Character, LongAdder> wordCounts = new ConcurrentHashMap<Character, LongAdder>();
Files.readAllLines(Paths.get(fileName))
.parallelStream()
.map(line -> line.split("\\s+"))
.flatMap(Arrays::stream)
.parallel()
.map(String::toLowerCase)
.forEach(word -> {
totalWords.increment();
char c = word.charAt(0);
if (!wordCounts.containsKey(c)) {
wordCounts.put(c, new LongAdder());
}
wordCounts.get(c).increment();
});
System.out.println(wordCounts);
System.out.println("Total word count: " + totalWords);
long end = Instant.now().toEpochMilli();
System.out.println(String.format("Completed in %d milliseconds", (end - start)));
}
public static void main(String[] args) throws Exception {
for (int r = 0; r < Integer.parseInt(args[1]); r++) {
new WordCount(args[0]).process();
}
}
}
vedresti conta variano come illustrato di seguito:
{a = 2, b = 3}
parola conteggio totale: 6
completata nel 77 millisecondi
{a = 3, b = 3}
Numero totale di parole: 6
Ora commenta ConcurrentHashMap alla riga 13, decommenta la riga sopra di esso ed esegui di nuovo il programma.
Si vedrebbero i conteggi deterministici.
fonte
2017-03-17 09:50:16
Quando si desidera ottenere ConcurrentHashMap, qual è il requisito del blocco di oggetti sincronizzati su questa istanza. – Anil
Sì, è necessario. – assylias