8
8
public class InvertedIndex {
9
9
10
10
private final Map <String , Map <String , Integer >> index ;
11
+ private final Object lock = new Object ();
11
12
12
13
public InvertedIndex () {
13
14
this .index = new HashMap <String , Map <String , Integer >>();
@@ -20,35 +21,39 @@ public InvertedIndex() {
20
21
* @param file
21
22
*/
22
23
public void indexWordInFile (final String word , final String file ) {
23
- // Get Existing index for the word or create a new list
24
- Map <String , Integer > fileMap = this .index .get (word );
25
- if (fileMap == null ) {
26
- fileMap = new HashMap <String , Integer >();
27
- fileMap .put (file , 1 );
28
- } else {
29
- // Add file and count to index of the word
30
- Integer countOfWords = fileMap .get (file );
31
- if (countOfWords == null ) {
32
- countOfWords = 0 ;
24
+ synchronized (lock ) {
25
+ // Get Existing index for the word or create a new list
26
+ Map <String , Integer > fileMap = this .index .get (word );
27
+ if (fileMap == null ) {
28
+ fileMap = new HashMap <String , Integer >();
29
+ fileMap .put (file , 1 );
30
+ } else {
31
+ // Add file and count to index of the word
32
+ Integer countOfWords = fileMap .get (file );
33
+ if (countOfWords == null ) {
34
+ countOfWords = 0 ;
35
+ }
36
+ fileMap .put (file , countOfWords + 1 );
33
37
}
34
- fileMap .put (file , countOfWords + 1 );
38
+ // Put back word's index to Directory's index
39
+ this .index .put (word , fileMap );
35
40
}
36
- // Put back word's index to Directory's index
37
- this .index .put (word , fileMap );
38
41
}
39
42
40
43
/**
41
44
* Returns the List of postings for a given word from the index
42
45
* @param word
43
46
*/
44
47
public List <Posting > getPostingsForWord (final String word ) {
45
- final Map <String , Integer > fileMap = this .index .get (word );
48
+ synchronized (lock ) {
49
+ final Map <String , Integer > fileMap = this .index .get (word );
46
50
47
- final List <Posting > postings = new ArrayList <Posting >();
48
- if (fileMap != null ) {
49
- fileMap .forEach ((file , frequency ) -> postings .add (new Posting (file , frequency )));
50
- }
51
+ final List <Posting > postings = new ArrayList <Posting >();
52
+ if (fileMap != null ) {
53
+ fileMap .forEach ((file , frequency ) -> postings .add (new Posting (file , frequency )));
54
+ }
51
55
52
- return postings ;
56
+ return postings ;
57
+ }
53
58
}
54
59
}
0 commit comments