Computer scienceProgramming languagesJavaWorking with dataMultithreadingSynchronization

Reentrant lock

Number to the power of 2

Report a typo

We can employ a lock reacquisition strategy to perform certain computations. Let's consider the task of identifying the smallest perfect square (a number raised to the power of 2) that is equal to or greater than a specific number. To do this, we can sequentially acquire a lock and, with each acquisition, multiply the initial number by 2. We continue this process until we reach a predetermined threshold. The total count of acquired locks can be determined using the getHoldCount() function, which will answer our question.

Here's your task: find the smallest perfect square (a number raised to the power of 2) that is equal to or larger than a given number.

To add a level of complexity, imagine we have three threads. Two of these threads act as registrars, reading and recording your current value. The third thread is tasked with performing the calculation.

Sample Input 1:

10

Sample Output 1:

4
Write a program in Java 17
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class SquareUpDown {
private int counter = 2;
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private int depth = 0;
private final int threshold;

public SquareUpDown(int threshold) {
this.threshold = threshold;
}

public void pow() {
lock.writeLock().lock();
try{
if (...) {
// Write your code here.
}
else {
depth = lock.writeLock().getHoldCount();
}
} finally{...}
}

public int getDegree() {
lock.readLock().lock();
try{...} finally{...}
// Write your code here...
}
}

// Protect code below...
public class Main {
private static final int COUNT_READ = 10;
___

Create a free account to access the full topic