Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package util;
- import java.io.IOException;
- import java.io.RandomAccessFile;
- import java.nio.ByteBuffer;
- import java.nio.file.Paths;
- import java.util.Arrays;
- import java.util.function.Consumer;
- import lombok.NonNull;
- import lombok.RequiredArgsConstructor;
- import lombok.val;
- /**
- * @author valekseev
- *
- * @since Oct 2, 2019
- */
- @RequiredArgsConstructor
- public class LockFileExecutionOperation<T> {
- private @NonNull final String lockFile;
- public void executeOnce(final @NonNull String checkValue, final @NonNull Consumer<T> operation, T object) throws IOException {
- try (val file = new RandomAccessFile(Paths.get(lockFile).toFile(), "rws")) {
- val lock = file.getChannel().lock();
- boolean executed = false;
- try {
- if (file.length() != 0) {
- lock.overlaps(0, file.length());
- val bb = ByteBuffer.allocate((int) file.length());
- lock.channel().read(bb, 0);
- executed = Arrays.equals(checkValue.getBytes(), bb.array());
- }
- if (!executed) {
- operation.accept(object);
- lock.channel().write(ByteBuffer.wrap(checkValue.getBytes()));
- }
- } finally {
- lock.release();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement