Skip to content

Instantly share code, notes, and snippets.

View aerodame's full-sized avatar

Steve Dame aerodame

View GitHub Profile
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
public class ConcurrentPartialFileLocking {
private static final String FILENAME = "concurrent_partial_locked_file.txt";
private static void createFileWithPhrase(String filename, String phrase) {
File file = new File(filename);
try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw")) {
randomAccessFile.write(phrase.getBytes()); // Write the string as bytes.
System.out.println("File " + filename + " created with the phrase: \"" + phrase + "\"");
} catch (IOException e) {
System.err.println("Error creating file: " + e.getMessage());
}
}
@Override
public void run() {
File file = new File(filename);
try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel channel = randomAccessFile.getChannel()) {
System.out.println(threadName + " attempting to acquire a lock on region [" +
startPosition + ", " + (startPosition + regionSize) + "]");
FileLock lock = null;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
public class FileLockingExample {
public static void main(String[] args) {
File file = new File("locked_file.txt");
private class C extends Thread
{
private Semaphore[] resource;
public C( Semaphore[] m ) {
resource = m;
}
public void run( ) {
System.out.println( "C started" );
synchronized ( resource[2] ) {
private class B extends Thread {
private Semaphore[] resource;
public B(Semaphore[] m) {
resource = m;
}
public void run() {
System.out.println("B started");
synchronized (resource[3]) {
private class A extends Thread {
private Semaphore[] resource;
public A(Semaphore[] m) {
resource = m;
}
public void run( ) {
System.out.println( "A started" );
synchronized ( resource[1] ) {
import java.util.concurrent.Semaphore;
public class Deadlock {
public Deadlock( ) {
Semaphore mutex[] = new Semaphore[4];
for ( int i = 0; i < 4; i++ )
mutex[i] = new Semaphore(1);
import java.util.Random;
public class App {
public static void main(String[] args) {
ResourceAllocator allocator = new ResourceAllocator();
// Example usage with multiple "Processes"
Runnable P0 = ( ) -> {
... // same code, different critical section time = 1000
};
Runnable P1 = () -> {
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ResourceAllocator {
private boolean busy;
private final Lock lock = new ReentrantLock();
private final Condition resourceAvailable = lock.newCondition();