Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. package util;
  2.  
  3. import java.io.IOException;
  4. import java.io.RandomAccessFile;
  5. import java.nio.ByteBuffer;
  6. import java.nio.file.Paths;
  7. import java.util.Arrays;
  8. import java.util.function.Consumer;
  9. import lombok.NonNull;
  10. import lombok.RequiredArgsConstructor;
  11. import lombok.val;
  12.  
  13. /**
  14. * @author valekseev
  15. *
  16. * @since Oct 2, 2019
  17. */
  18. @RequiredArgsConstructor
  19. public class LockFileExecutionOperation<T> {
  20.  
  21. private @NonNull final String lockFile;
  22.  
  23. public void executeOnce(final @NonNull String checkValue, final @NonNull Consumer<T> operation, T object) throws IOException {
  24. try (val file = new RandomAccessFile(Paths.get(lockFile).toFile(), "rws")) {
  25. val lock = file.getChannel().lock();
  26. boolean executed = false;
  27. try {
  28. if (file.length() != 0) {
  29. lock.overlaps(0, file.length());
  30. val bb = ByteBuffer.allocate((int) file.length());
  31. lock.channel().read(bb, 0);
  32. executed = Arrays.equals(checkValue.getBytes(), bb.array());
  33. }
  34. if (!executed) {
  35. operation.accept(object);
  36. lock.channel().write(ByteBuffer.wrap(checkValue.getBytes()));
  37. }
  38. } finally {
  39. lock.release();
  40. }
  41. }
  42. }
  43.  
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement