Skip to content
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

Merged
merged 28 commits into from Dec 9, 2016
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
0866a60
Merge remote-tracking branch 'refs/remotes/fediq/master'
vanderwardan Nov 1, 2016
552d60a
Merge remote-tracking branch 'refs/remotes/fediq/master'
vanderwardan Nov 20, 2016
3b50057
Add third task
vanderwardan Nov 21, 2016
da7781b
Merge remote-tracking branch 'refs/remotes/fediq/master'
vanderwardan Nov 21, 2016
10c6e3d
Third task
vanderwardan Nov 21, 2016
2f58fa2
Codestyle changes
vanderwardan Nov 21, 2016
a9c4c95
add synchronised
vanderwardan Nov 21, 2016
a9f1fc8
Review changes
vanderwardan Nov 27, 2016
f530f07
code style changes
vanderwardan Nov 27, 2016
83ecff4
try do smth, that travis test my project
vanderwardan Nov 27, 2016
6446586
tried again
vanderwardan Nov 27, 2016
181536f
add cleaning storage not only in close()
vanderwardan Nov 27, 2016
af9170b
code style changes
vanderwardan Nov 27, 2016
a9a52c0
revert
vanderwardan Nov 27, 2016
f95b2d3
some bugs fixed
vanderwardan Nov 27, 2016
a85598c
try find what's wrong with travis
vanderwardan Nov 27, 2016
0ccfc8a
code style
vanderwardan Nov 27, 2016
e81d659
and here we go
vanderwardan Nov 27, 2016
81e49f0
optimise little bit
vanderwardan Nov 28, 2016
12319c8
oops
vanderwardan Nov 29, 2016
b1b8e2b
Merge remote-tracking branch 'refs/remotes/fediq/master'
vanderwardan Dec 4, 2016
e328d85
try to pass new tests
vanderwardan Dec 4, 2016
8722b58
fix problems with seek
vanderwardan Dec 5, 2016
89423e5
fix problems with files
vanderwardan Dec 5, 2016
6c53bd8
code style changes
vanderwardan Dec 5, 2016
eacb2e4
fix constructor
vanderwardan Dec 5, 2016
edcfe73
back to the right version of lector's file
vanderwardan Dec 9, 2016
47dde1d
fucking IDEA auto fixes
vanderwardan Dec 9, 2016
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 0 additions & 1 deletion homework-g595-manucharyan/pom.xml
Expand Up @@ -10,7 +10,6 @@
<modelVersion>4.0.0</modelVersion>

<artifactId>homework-g595-manucharyan</artifactId>
<packaging>pom</packaging>
<version>1.0.0</version>

<dependencies>
Expand Down
@@ -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();
}
}
@@ -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();
}
}
@@ -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();
}

}
@@ -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)) {
Copy link
Collaborator

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), а ты её игноришь. Не надо так.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну так же понятней, нет? Типа тут односложные ифы, и сразу понятно, что происходит, иначе надо думать(

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну, не знаю, по мне так два однотипных условия в одном выглядят читабельнее. Вообще не суть.

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() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

При повторном закрытии ничего не нужно делать. У тебя нет этой проверки.

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

try-with-resources здесь хорошо подходит.

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Через DataOutputStream можно было бы наклепать, обернув BufferedOutputStream. Побыстрее должно работать.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

мне же нужно знать offset для каждого элемента, а у DataOutputStream нет такого функционала, или я что-то не понимаю?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

size()

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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");
}
}
}

@@ -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;
}
@@ -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());
}
}