New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
g595.Manucharyan.task3 #279
Changes from 18 commits
0866a60
552d60a
3b50057
da7781b
10c6e3d
2f58fa2
a9c4c95
a9f1fc8
f530f07
83ecff4
6446586
181536f
af9170b
a9a52c0
f95b2d3
a85598c
0ccfc8a
e81d659
81e49f0
12319c8
b1b8e2b
e328d85
8722b58
89423e5
6c53bd8
eacb2e4
edcfe73
47dde1d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package ru.mipt.java2016.homework.g595.manucharyan.task3; | ||
|
||
import java.io.DataInput; | ||
import java.io.DataOutput; | ||
import java.io.IOException; | ||
|
||
/** | ||
* @author Vardan Manucharyan | ||
* @since 30.10.16 | ||
*/ | ||
public class ConcreteStrategyDoubleRandomAccess implements SerializationStrategyRandomAccess<Double> { | ||
@Override | ||
public void serializeToFile(Double value, DataOutput output) throws IOException { | ||
output.writeDouble(value); | ||
} | ||
|
||
@Override | ||
public Double deserializeFromFile(DataInput input) throws IOException { | ||
return input.readDouble(); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package ru.mipt.java2016.homework.g595.manucharyan.task3; | ||
|
||
import java.io.DataInput; | ||
import java.io.DataOutput; | ||
import java.io.IOException; | ||
|
||
/** | ||
* @author Vardan Manucharyan | ||
* @since 30.10.16 | ||
*/ | ||
public class ConcreteStrategyIntegerRandomAccess implements SerializationStrategyRandomAccess<Integer> { | ||
@Override | ||
public void serializeToFile(Integer value, DataOutput output) throws IOException { | ||
output.writeInt(value); | ||
} | ||
|
||
@Override | ||
public Integer deserializeFromFile(DataInput input) throws IOException { | ||
return input.readInt(); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
package ru.mipt.java2016.homework.g595.manucharyan.task3; | ||
|
||
import java.io.DataInput; | ||
import java.io.DataOutput; | ||
import java.io.IOException; | ||
|
||
/** | ||
* @author Vardan Manucharyan | ||
* @since 30.10.16 | ||
*/ | ||
public class ConcreteStrategyStringRandomAccess implements SerializationStrategyRandomAccess<String> { | ||
@Override | ||
public void serializeToFile(String value, DataOutput output) throws IOException { | ||
output.writeUTF(value); | ||
} | ||
|
||
@Override | ||
public String deserializeFromFile(DataInput input) throws IOException { | ||
return input.readUTF(); | ||
} | ||
|
||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,278 @@ | ||
package ru.mipt.java2016.homework.g595.manucharyan.task3; | ||
|
||
import java.io.File; | ||
import java.io.IOException; | ||
import java.io.RandomAccessFile; | ||
import java.util.HashMap; | ||
import java.util.Iterator; | ||
import java.util.Map; | ||
|
||
import ru.mipt.java2016.homework.base.task2.KeyValueStorage; | ||
|
||
/** | ||
* @author Vardan Manucharyan | ||
* @since 20.11.2016. | ||
*/ | ||
public class OptimisedKeyValueStorage<K, V> implements KeyValueStorage<K, V> { | ||
|
||
private static final long MAX_CACHE_SIZE = 100L; | ||
private static final double FILLING_PERCENTAGE = 0.5; //when we need clean storage from deleted values | ||
private static long deletedCount; //number of deleted elements | ||
|
||
private final SerializationStrategyRandomAccess<K> keySerializationStrategy; | ||
private final SerializationStrategyRandomAccess<V> valueSerializationStrategy; | ||
|
||
//consist keys and offsets(the pair of begin and length) | ||
private Map<K, Long> base = new HashMap<>(); | ||
private Map<K, V> cache = new HashMap<>(); | ||
|
||
private long maxOffset; | ||
private final String pathname; | ||
private final String storageName = "storage.txt"; | ||
private RandomAccessFile mapStorage; | ||
private final String mapStorageName = "mapStorage.txt"; | ||
|
||
private File mutexFile; // для многопоточности | ||
private boolean isClosed; | ||
|
||
public OptimisedKeyValueStorage(SerializationStrategyRandomAccess<K> keySerializationStrategy, | ||
SerializationStrategyRandomAccess<V> valueSerializaionStrategy, | ||
String path) throws IOException { | ||
|
||
this.keySerializationStrategy = keySerializationStrategy; | ||
this.valueSerializationStrategy = valueSerializaionStrategy; | ||
maxOffset = 0L; | ||
deletedCount = 0L; | ||
pathname = path; | ||
isClosed = false; | ||
|
||
mutexFile = new File(pathname, "Mutex"); | ||
if (!mutexFile.createNewFile()) { | ||
throw new RuntimeException("Can't synchronize!"); | ||
} | ||
|
||
File directory = new File(pathname); | ||
if (!directory.isDirectory()) { | ||
throw new RuntimeException("wrong path"); | ||
} | ||
|
||
try { | ||
File file2 = new File(path, mapStorageName); | ||
mapStorage = new RandomAccessFile(file2, "rw"); | ||
|
||
downloadDataFromStorage(); | ||
} catch (IOException exception) { | ||
throw new RuntimeException("Can't create a storage!"); | ||
} | ||
} | ||
|
||
/** | ||
* Возвращает значение для данного ключа, если оно есть в хранилище. | ||
* Иначе возвращает null. | ||
*/ | ||
@Override | ||
public synchronized V read(K key) { | ||
if (!exists(key)) { | ||
return null; | ||
} else { | ||
try { | ||
if (cache.get(key) != null) { | ||
return cache.get(key); | ||
} | ||
File file = new File(pathname, storageName); | ||
RandomAccessFile storage = new RandomAccessFile(file, "rw"); | ||
|
||
Long offset = base.get(key); | ||
storage.seek(offset); | ||
V res = valueSerializationStrategy.deserializeFromFile(storage); | ||
storage.close(); | ||
return res; | ||
} catch (Exception exception) { | ||
throw new RuntimeException("Can't read from storage"); | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* Возвращает true, если данный ключ есть в хранилище | ||
*/ | ||
@Override | ||
public boolean exists(K key) { | ||
isClose(); | ||
|
||
if (cache.containsKey(key)) { | ||
return true; | ||
} | ||
return base.containsKey(key); | ||
} | ||
|
||
/** | ||
* Записывает в хранилище пару ключ-значение. | ||
*/ | ||
@Override | ||
public synchronized void write(K key, V value) { | ||
isClose(); | ||
|
||
cache.put(key, value); | ||
base.put(key, 0L); | ||
|
||
if (cache.size() > MAX_CACHE_SIZE) { | ||
writeCacheToStorage(); | ||
} | ||
} | ||
|
||
/** | ||
* Удаляет пару ключ-значение из хранилища. | ||
*/ | ||
@Override | ||
public synchronized void delete(K key) { | ||
isClose(); | ||
|
||
cache.remove(key); | ||
base.remove(key); | ||
deletedCount++; | ||
|
||
if (deletedCount / size() > FILLING_PERCENTAGE) { | ||
reorganiseStorage(); | ||
} | ||
} | ||
|
||
/** | ||
* Читает все ключи в хранилище. | ||
* <p> | ||
* Итератор должен бросать {@link java.util.ConcurrentModificationException}, | ||
* если данные в хранилище были изменены в процессе итерирования. | ||
*/ | ||
@Override | ||
public Iterator<K> readKeys() { | ||
isClose(); | ||
|
||
return base.keySet().iterator(); | ||
|
||
} | ||
|
||
/** | ||
* Возвращает число ключей, которые сейчас в хранилище. | ||
*/ | ||
@Override | ||
public int size() { | ||
isClose(); | ||
|
||
return base.size(); | ||
} | ||
|
||
@Override | ||
public synchronized void close() { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. При повторном закрытии ничего не нужно делать. У тебя нет этой проверки. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Да, точно |
||
if (isClosed) { | ||
return; | ||
} | ||
|
||
reorganiseStorage(); | ||
uploadDataToStorage(); | ||
|
||
try { | ||
mapStorage.close(); | ||
} catch (IOException excetion) { | ||
throw new RuntimeException("Can't close storage"); | ||
} finally { | ||
isClosed = true; | ||
cache.clear(); | ||
base.clear(); | ||
mutexFile.delete(); | ||
} | ||
} | ||
|
||
private void downloadDataFromStorage() { | ||
try { | ||
|
||
int count = -1; | ||
count = mapStorage.readInt(); | ||
|
||
for (int i = 0; i < count; i++) { | ||
K key = keySerializationStrategy.deserializeFromFile(mapStorage); | ||
Long tmp = mapStorage.readLong(); | ||
base.put(key, tmp); | ||
maxOffset = Math.max(maxOffset, tmp); | ||
} | ||
} catch (IOException exception) { | ||
base.clear(); | ||
//throw new RuntimeException("Trouble with storage.db"); | ||
} | ||
} | ||
|
||
private void uploadDataToStorage() { | ||
try { | ||
mapStorage.close(); | ||
File file = new File(pathname, mapStorageName); | ||
assert (file.delete()); | ||
file = new File(pathname, mapStorageName); | ||
mapStorage = new RandomAccessFile(file, "rw"); | ||
|
||
mapStorage.writeInt(size()); | ||
for (HashMap.Entry<K, Long> entry : base.entrySet()) { | ||
keySerializationStrategy.serializeToFile(entry.getKey(), mapStorage); | ||
mapStorage.writeLong(entry.getValue()); | ||
} | ||
} catch (IOException exception) { | ||
throw new RuntimeException("Trouble with storage.db"); | ||
} | ||
} | ||
|
||
private void writeCacheToStorage() { | ||
isClose(); | ||
try { | ||
File file = new File(pathname, storageName); | ||
RandomAccessFile storage = new RandomAccessFile(file, "rw"); | ||
|
||
for (HashMap.Entry<K, V> entry : cache.entrySet()) { | ||
storage.seek(maxOffset); | ||
valueSerializationStrategy.serializeToFile(entry.getValue(), storage); | ||
long curOffset = storage.getFilePointer(); | ||
base.put(entry.getKey(), maxOffset); | ||
maxOffset = curOffset; | ||
} | ||
storage.close(); | ||
cache.clear(); | ||
|
||
} catch (IOException exception) { | ||
throw new RuntimeException("Can't write cache on the disk"); | ||
} | ||
|
||
} | ||
|
||
private void reorganiseStorage() { | ||
try { | ||
File file1 = new File(pathname, storageName); | ||
RandomAccessFile storage = new RandomAccessFile(file1, "rw"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. try-with-resources здесь хорошо подходит. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Добавил |
||
|
||
File file = new File(pathname, "newStorage.txt"); | ||
RandomAccessFile newStorage = new RandomAccessFile(file, "rw"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Через There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. мне же нужно знать offset для каждого элемента, а у DataOutputStream нет такого функционала, или я что-то не понимаю? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Да, стало работать быстрее, спасибо) |
||
|
||
writeCacheToStorage(); | ||
|
||
for (HashMap.Entry<K, Long> entry : base.entrySet()) { | ||
storage.seek(entry.getValue()); | ||
Long tmp = newStorage.getFilePointer(); | ||
valueSerializationStrategy.serializeToFile(read(entry.getKey()), newStorage); | ||
base.put(entry.getKey(), tmp); | ||
} | ||
deletedCount = 0; | ||
|
||
storage.close(); | ||
assert (file1.delete()); | ||
|
||
newStorage.close(); | ||
assert (file.renameTo(file1)); | ||
|
||
} catch (IOException exception) { | ||
throw new RuntimeException("Can't reorganise storage!"); | ||
} | ||
} | ||
|
||
private void isClose() { | ||
if (isClosed) { | ||
throw new IllegalStateException("Can't write: storage is closed"); | ||
} | ||
} | ||
} | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package ru.mipt.java2016.homework.g595.manucharyan.task3; | ||
|
||
import java.io.DataInput; | ||
import java.io.DataOutput; | ||
import java.io.IOException; | ||
|
||
/** | ||
* @author Vardan Manucharyan | ||
* @since 30.10.16 | ||
*/ | ||
public interface SerializationStrategyRandomAccess<Value> { | ||
|
||
void serializeToFile(Value value, DataOutput output) throws IOException; | ||
|
||
Value deserializeFromFile(DataInput input) throws IOException; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
package ru.mipt.java2016.homework.g595.manucharyan.task3; | ||
|
||
import java.io.DataInput; | ||
import java.io.DataOutput; | ||
import java.io.IOException; | ||
|
||
import ru.mipt.java2016.homework.tests.task2.StudentKey; | ||
|
||
/** | ||
* @author Vardan Manucharyan | ||
* @since 30.10.16 | ||
*/ | ||
public class ConcreteStrategyStudentKeyRandomAccess implements SerializationStrategyRandomAccess<StudentKey> { | ||
|
||
@Override | ||
public void serializeToFile(StudentKey value, DataOutput output) throws IOException { | ||
output.writeInt(value.getGroupId()); | ||
output.writeUTF(value.getName()); | ||
} | ||
|
||
@Override | ||
public StudentKey deserializeFromFile(DataInput input) throws IOException { | ||
return new StudentKey(input.readInt(), input.readUTF()); | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Идея предложила тебе заменить на
return cache.containsKey(key) || base.containsKey(key)
, а ты её игноришь. Не надо так.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ну так же понятней, нет? Типа тут односложные ифы, и сразу понятно, что происходит, иначе надо думать(
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ну, не знаю, по мне так два однотипных условия в одном выглядят читабельнее. Вообще не суть.