-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Created class to periodically extract some word from the dictionary. …
…Thread-safe implementation on the current extracted word.
- Loading branch information
1 parent
93b1f39
commit 1aacee1
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
package server.service; | ||
|
||
import java.io.RandomAccessFile; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.Random; | ||
|
||
/** | ||
* Word extraction service. | ||
* Periodically extract a new word from the dictionary. | ||
*/ | ||
public class WordExtractionService extends Thread { | ||
|
||
public static volatile String currentWord; | ||
private static final List<String> dictionary; | ||
private static final List<String> extractedWords; | ||
|
||
static { | ||
extractedWords = new ArrayList<>(); | ||
dictionary = new ArrayList<>(); | ||
try (final RandomAccessFile file = | ||
new RandomAccessFile("src/main/java/server/conf/words.txt", "r")) { | ||
String line = file.readLine(); | ||
while (line != null) { | ||
dictionary.add(line); | ||
line = file.readLine(); | ||
} | ||
} catch (Exception e) { | ||
System.out.println("Error reading words from file."); | ||
} | ||
} | ||
|
||
|
||
/** | ||
* Constructor for WordExtractionService. | ||
*/ | ||
public WordExtractionService() { | ||
} | ||
|
||
|
||
/** | ||
* Runs the service. | ||
*/ | ||
@Override | ||
public void run() { | ||
this.extractWord(); | ||
} | ||
|
||
|
||
/** | ||
* Randomly extracts a new word from the dictionary. | ||
*/ | ||
private void extractWord() { | ||
|
||
final Random random = new Random(); | ||
final List<String> notExtractedWords = | ||
dictionary.stream().filter(word -> !extractedWords.contains(word)).toList(); | ||
final String word = dictionary.get(random.nextInt(notExtractedWords.size())); | ||
extractedWords.add(word); | ||
currentWord = word; | ||
|
||
} | ||
|
||
|
||
} |