Cadence Inc Interview Question for Principal Software Engineers


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
0
of 0 vote

This is how I'd do it,
use counting semaphores for resources
thread will acquire required resources and process for a certain amount of time
release after the sleep
Note : variable time , t and sleep(t) have been used for fine tuning the start time of threads
and would not be required if its too much trouble

public class EgThread {
    private static final Semaphore sem = new Semaphore(10);
    private static final long time = System.currentTimeMillis() + 5000; // not required
    
    public static void main(String[] args) {
        MyThread[] threads = new MyThread[5];
        
        for (int i = 0; i < 5; i++) {
            threads[i] = new MyThread(String.valueOf(i + 1));
        }
        for (int i = 0; i < 5; i++)
            threads[i].start();
        
        try {
            for (int i = 0; i < 5; i++)
                threads[i].join();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    static class MyThread extends Thread {
        String name;
        
        MyThread(String name) {
            this.name = name;
        }
        
        @Override
        public void run() {
            try {
                long t = time - System.currentTimeMillis(); // not required
                sleep(t); //---------------------------------- not required
                for (int i = 0; i < 10; i++) {
                    int req = (int) (6 * Math.random()) + 1;
                    System.out.println("T[" + name + "] run : " + (i + 1) + " asks for " + req + " resources");
                    sem.acquire(req);
                    System.out.println("T[" + name + "] run : " + (i + 1) + " acquires " + req + " resources");
                    sleep((long) (500 * Math.random()) + 200);
                    System.out.println("T[" + name + "] run : " + (i + 1) + " releases " + req + " resources");
                    sem.release(req);
                }
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

- PeyarTheriyaa November 11, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is a good start, but it does not satisfy the "in order" requirement. It's a greedy algorithm that would starve large requests.

- Anonymous March 28, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Hi, Please share your answers ? will try our level best but could not get.

- Dowlath June 19, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Application {

	public static void main(String arg[]) {
		
		ResourceSharing sharedResource = new ResourceSharing(10, 5);
		
		Task tasks [] = new Task[5];
		
		IntStream.range(0, tasks.length).forEach(i -> {
			tasks[i] = new Task(++i, 2+i, sharedResource);
		});
		
		ExecutorService executorService = Executors.newCachedThreadPool();
		Arrays.stream(tasks).forEach(executorService::execute);
		
	}
}


public class Task implements Runnable {

	private int threadNum;
	
	private int requiredResources;
	
	private ResourceSharing sharedResource;
	
	public Task(int threadNum, int requiredResources, ResourceSharing sharedResource) {
		super();
		this.threadNum = threadNum;
		this.requiredResources = requiredResources;
		this.sharedResource = sharedResource;
	}

	@Override
	public void run() {
		try {
			sharedResource.executeUsingResource(threadNum, requiredResources);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}



package phlilospher.sequence;

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ResourceSharing {

	final private int totalResources;
	
	final private int totalConsumers;
	
	final private Semaphore semaphore;
	
	final private Lock lock;
	
	final private Condition isNotInOrder;
	
	private AtomicInteger currentOrder = new AtomicInteger(1);
	
	public ResourceSharing(int totalResources, int totalConsumers) {
		super();
		this.totalResources = totalResources;
		this.totalConsumers =  totalConsumers;
		this.semaphore = new Semaphore(totalResources);
		this.lock = new ReentrantLock();
		this.isNotInOrder = lock.newCondition();
	}
	
	public void executeUsingResource(int orderNo, int resources) throws InterruptedException {
		if(resources > totalResources || orderNo > totalConsumers)
			throw new IllegalArgumentException();
		lock.lock();
		try {
			while(orderNo != currentOrder.get())
				isNotInOrder.await();
			
			semaphore.acquire(resources);
			System.out.println("Thread : " + orderNo+ " running using resource : "+resources);
			Thread.sleep(10);
			System.out.println("Thread : " + orderNo+ " freeing resource : "+resources);
			semaphore.release(resources);
			
			currentOrder.getAndIncrement();
			isNotInOrder.signalAll();
		} finally {
			lock.unlock();
		}
	}
}

- MatSib July 07, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

lock in beginning of the method executeUsingResource will always allow only one thread to execute regardless the available resources
For example : thread t1 using 3 out of 10 resources will hold the lock
thread t2 using 4 out of 7 available resources will wait until t1 releases the lock.

{{
public class ResourceSharing {

final private int totalResources;

final private int totalConsumers;

final private Semaphore semaphore;

private AtomicInteger currentOrder = new AtomicInteger(1);

public ResourceSharing(int totalResources, int totalConsumers) {
super();
this.totalResources = totalResources;
this.totalConsumers = totalConsumers;
this.semaphore = new Semaphore(totalResources);
}

public void executeUsingResource(int orderNo, int resources) throws InterruptedException {
if(resources > totalResources || orderNo > totalConsumers)
throw new IllegalArgumentException();
while(orderNo != currentOrder.get()) {
//busy wait;
Thread.sleep(10);
}
semaphore.acquire(resources);
try {
currentOrder.getAndIncrement();
System.out.println("Thread : " + orderNo+ " running using resource : "+resources);
Thread.sleep(1000);
System.out.println("Thread : " + orderNo+ " freeing resource : "+resources);
} finally {
semaphore.release(resources);
}
}
}
}}
Output :
Thread : 1 running using resource : 3
Thread : 2 running using resource : 4
Thread : 1 freeing resource : 3
Thread : 3 running using resource : 5
Thread : 2 freeing resource : 4
Thread : 3 freeing resource : 5
Thread : 4 running using resource : 6
Thread : 4 freeing resource : 6
Thread : 5 running using resource : 7
Thread : 5 freeing resource : 7

- Anonymous July 09, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ResourceSharing {

	final private int totalResources;
	
	final private int totalConsumers;
	
	final private Semaphore semaphore;
	
	final private Lock lock;
	
	final private Condition isNotInOrder;
	
	private AtomicInteger currentOrder = new AtomicInteger(1);
	
	public ResourceSharing(int totalResources, int totalConsumers) {
		super();
		this.totalResources = totalResources;
		this.totalConsumers =  totalConsumers;
		this.semaphore = new Semaphore(totalResources);
		this.lock = new ReentrantLock();
		this.isNotInOrder = lock.newCondition();
	}
	
	public void executeUsingResource(int orderNo, int resources) throws InterruptedException {
		if(resources > totalResources || orderNo > totalConsumers)
			throw new IllegalArgumentException();
		lock.lock();
		try {
			while(orderNo != currentOrder.get())
				isNotInOrder.await();
			
			semaphore.acquire(resources);
			System.out.println("Thread : " + orderNo+ " running using resource : "+resources);
			Thread.sleep(10);
			System.out.println("Thread : " + orderNo+ " freeing resource : "+resources);
			semaphore.release(resources);
			
			currentOrder.getAndIncrement();
			isNotInOrder.signalAll();
		} finally {
			lock.unlock();
		}
	}
}

- Anonymous July 07, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

After the software development process, the software is optimized for real-time usage. This means that new versions of the software have to be made available to customers as soon as possible so that they can use it right away. After that, the software is deployed to a production environment to ensure that it is able to meet the expectations of the customer. During the production phase, the software is continuously improved and updated to make it more efficient https://mlsdev.com/services/custom-software-development. This phase of software development also includes improvements such as bug fixing, documentation improvement, documentation revamping and web site maintenance.

- judeyangels August 16, 2021 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More