Site icon

Concurrency – Synchronize resources using ReentrantLock in java (example)

1. TransferFile Class:

package org.learn.sync.lk;

import java.io.File;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static java.lang.Thread.sleep;

public class TransferFile {

    private Lock lock = new ReentrantLock();
    private Random random = new Random();

    public void transfer(File file/*file to transfer*/) {

        int time = random.nextInt(200);
        lock.lock();
        try {
            System.out.printf("Sending file to another machine,time required: %d\n", time);
            //transferring file to another server machine
            sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

2. FileTransferJob Class:

package org.learn.sync.lk;

import java.io.File;

public class FileTransferJob extends Thread {

    private TransferFile transferFile;

    public FileTransferJob(TransferFile transferFile) {
        this.transferFile = transferFile;
    }

    @Override
    public void run() {
        File dummyFile = new File("");
        System.out.printf("%s, Start sending dummy file to another machine\n",getName());
        transferFile.transfer(dummyFile);
        System.out.printf("%s,Successfully sent file to another machine\n",getName());
    }
}

3. LockExample Class:

package org.learn.sync.lk;

public class LockExample {

    public static void main(String[] args) throws InterruptedException {

        for(int job = 0 ; job < 5; job++) {
            FileTransferJob transferJob = new FileTransferJob(new TransferFile());
            transferJob.start();
        }
    }
}

4. Output: Synchronize resources using ReentrantLock in java (example)

Thread-0, Start sending dummy file to another machine
Thread-4, Start sending dummy file to another machine
Thread-3, Start sending dummy file to another machine
Thread-2, Start sending dummy file to another machine
Thread-1, Start sending dummy file to another machine
Sending file to another machine,time required: 47
Sending file to another machine,time required: 81
Sending file to another machine,time required: 126
Sending file to another machine,time required: 8
Sending file to another machine,time required: 44
Thread-0,Successfully sent file to another machine
Thread-1,Successfully sent file to another machine
Thread-2,Successfully sent file to another machine
Thread-3,Successfully sent file to another machine
Thread-4,Successfully sent file to another machine
Exit mobile version