Barclays Capital Interview Question for Senior Software Development Engineers


Country: United States




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

Don't see the point in the question.
call run of B in run of A and so on. Seems a warm up question.

- EK MACHCHAR May 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Here is the solution...

public class InsteadJoin {

	public Thread createThread(String name){
		Thread t = new Thread(name){
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName());
			}
		};
		return t;
	}
	
	public void myJoin(Thread t){
		while(t.isAlive()){
			
		}
	}
	
	public static void main(String[] args) {
		InsteadJoin ij = new InsteadJoin();
		System.out.println("Start");
		Thread t = ij.createThread("A");
		Thread t1 = ij.createThread("B");
		Thread t2 = ij.createThread("C");
		
		t.start();
		ij.myJoin(t);
		
		t1.start();
		ij.myJoin(t1);
		
		t2.start();
		ij.myJoin(t2);
		
		System.out.println("Done");
	}

}

- Rambrij Chauhan December 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

i think at the end of each thread's function you need to mark a flag that says it has ended its work, and make a while loop that checks the flags of the other threads, waiting for them to finish. a pthread_join page suggested that.

- yuval May 20, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The simplest answer is

Thread1.run();
Thread2.run();
Thread3.run();
The problem with unrealistic questions is they often have an uninformative answer. ;)

The whole point of having threads is to run them concurrently. If you are not doing that at all, don't use threads.

You might say that; you cannot call the run() method, in which case you cannot use ThreadPoolExecutor because it calls the run() method for you. i.e. thats what submit() eventually does.

EDIT: The results are completely deterministic, becaus ethe fact that there is a Thread involved is irrelivent.

static class PrintThread extends Thread {
public PrintThread(String name) {
super(name);
}

@Override
public void run() {
for (int i = 0; i < 100; i++)
System.out.println(getName() + ": " + i);
}
}

public static void main(String args[]) {
Thread thread1 = new PrintThread("A");
Thread thread2 = new PrintThread("B");
Thread thread3 = new PrintThread("C");

thread1.run();
thread2.run();
thread3.run();
}
Prints

A: 0
A: 1
.. deleted ..
C: 98
C: 99

- ram.soft2003 May 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

i think the answer they wanted is quite obvious - force threads to either wait on a CyclicBarrier or use CountDownLatch to make sure they will start at moreless same point in time

- nlazarev84 June 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

can be done by giving threads their sequence and when the running value equals that value then the thread is allowed to run

as below
class resource
{


private int sequence;

public resource(int i) {
this.sequence=i;
}


public int getSequence() {
return sequence;
}

public synchronized void incementSequence()
{
sequence++;
}

}

class sequence implements Runnable

{

int sequence;
resource obj;

public sequence(int i,resource obj) {

this.sequence=i;
this.obj=obj;
}

public void run() {


synchronized(obj)
{
while(obj.getSequence()!=sequence)
{
try {
obj.wait();
} catch (InterruptedException ex) {
Logger.getLogger(sequence.class.getName()).log(Level.SEVERE, null, ex);
}
}

System.out.println("my processing is done with sequence->"+sequence);
obj.incementSequence();
obj.notifyAll();
}
}



}





public class sequenceRunning {



public static void main(String args[])
{


sequence obj[]=new sequence[3];
resource objresource=new resource(1);
for(int i=0;i<3;i++)
{
obj[i]=new sequence(i+1,objresource);
Thread runThread=new Thread(obj[i]);
runThread.start();
}



}



}

- blackfever July 15, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Perhaps the OP meant to say that the 3 thread can be started in any order.

R implements Runnable {
		private Semaphore s1;
		private Semaphore s2;
		public R(Semaphore s1, Semaphore s2) {
			this.s1 = s1;
			this.s2 = s2;
		}
		
		public void run() {
			// Wait until s1 is released
			if (s1 != null)
				s1.aquire();
			// Do some work here
			if (s1 != null)
				s1.release();
			// Allow the thread that is waiting for s2 to proceed
			if (s2 != null)
				s2.release();
		}

		public static void main(...) {
			Semaphore s2 = new Semaphore(0);
			Semaphore s3 = new Semaphore(0);
			Thread t1 = new Thread(new R(null, s2));
			Thread t2 = new Thread(new R(s2, s3));
			Thread t3 = new Thread(new R(s3, null));
			t1.start();
			t2.start();
			t3.start();
		}
	}

- Anonymous September 08, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

You may find this solution bit expensive but condition variable can be used to synchronize these threads sequentially

#include <pthread.h>
#include <stdio.h>

pthread_mutex_t mt = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void * th3_impl(void *)
{
   pthread_mutex_lock(&mt);
   printf("Inside third thread\n");
   pthread_cond_signal(&cond);
   pthread_mutex_unlock(&mt);
}

void * th2_impl(void *)
{
   pthread_mutex_lock(&mt);
   printf("Inside second thread\n");
   pthread_cond_signal(&cond);
   pthread_mutex_unlock(&mt);
}

void * th1_impl(void *)
{
   pthread_mutex_lock(&mt);
   printf("Inside first thread\n");
   pthread_cond_signal(&cond);
   pthread_mutex_unlock(&mt);
}

int main()
{
   pthread_t th1,th2,th3;
   pthread_mutex_lock(&mt);
   pthread_create(&th1, NULL, &th1_impl, NULL);
   pthread_cond_wait(&cond,&mt);
   pthread_mutex_unlock(&mt);

   pthread_mutex_lock(&mt);
   pthread_create(&th2, NULL, &th2_impl, NULL);
   pthread_cond_wait(&cond,&mt);
   pthread_mutex_unlock(&mt);

   pthread_mutex_lock(&mt);
   pthread_create(&th3, NULL, &th3_impl, NULL);
   pthread_cond_wait(&cond,&mt);
   pthread_mutex_unlock(&mt);
}

- Ashutosh September 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

It should be possible to use a FIFO mutex as well to solve this problem. It allows the mutex to be passed to next thread in queue.

Where to use :

Assume two threads T1 and T2 are trying to execute a critical section. Both don't have much to do outside this critical section and hold locks for a good amount of time. So, T1 may lock, execute and unlock and signal T2 for wakeup. But before T2 could wakeup and acquire lock, T1 reacquires lock and execute. In this way, T2 may have to wait a very long time before it actually gets the lock or may be not.

How it works / How to implement :

Have a mutex to lock on. Initialize Thread Specific Data (TSD) for each thread to a node containing thread id and semaphore. Also, have two variables - owned (TRUE or FALSE or -1), owner (owner thread id). In addition, keep a waiters queue and a pointer waiterLast pointing to last node in waiters queue.

lock operation :

node = get_thread_specific_data(node_key);
lock(mutex);
    if(!owned)
    {
        owned = true;
        owner = self;
        return success;
    }

    node->next = nullptr;
    if(waiters_queue == null) waiters_queue = node;
    else waiters_last->next = node;

    waiters_last = node;
unlock(mutex);
sem_wait(node->semaphore);

lock(mutex);
    if(owned != -1) abort();
    owned = true;
    owner = self;
    waiters_queue = waiters_queue->next;
 unlock(mutex);

unlock operation :

lock(mutex);
    owner = null;
    if(waiters_queue == null)
    {
        owned = false;
        return success;
    }
    owned = -1;
    sem_post(waiters_queue->semaphore);
unlock(mutex);

- nilukush October 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Synchronizing threads without using join method is possible. If you are aware of wait(), notify() and notifyAll() methods, so can might be aware of the use of this methods. You can synchronize you thread with the help of these important methods. If you want to see good real implementation of this you can visit below given this link where you can see good example of this.

somanyword.com/2013/11/how-to-make-threads-in-sequence-execution-without-using-join/

- Manoj Sharma December 09, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

see here example related to this question
<a href="somanyword.com/2013/11/how-to-make-threads-in-sequence-execution-without-using-join/">Click here</a>

- maddy January 07, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

use conditional variable to make the threads run sequentially.

- Passerby_A March 07, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<pthread.h>
#include<stdio.h>

int num_threads=3;
int state=0;
pthread_cond_t cond;
pthread_mutex_t mutex;

void* threadA(void* args) {

int i;
for(i=0; i<5; i++){

pthread_mutex_lock(&mutex);

while(state == 1 || state == 2) pthread_cond_wait(&cond,&mutex);

printf("Thread A\n");
state = (state+1)%num_threads;
pthread_cond_signal(&cond);

pthread_mutex_unlock(&mutex);

}
}

void* threadB(void* args) {

int i;
for(i=0; i<5; i++){

pthread_mutex_lock(&mutex);

while(state == 0 || state == 2)pthread_cond_wait(&cond,&mutex);

printf("Thread B\n");
state = (state+1)%num_threads;
pthread_cond_signal(&cond);

pthread_mutex_unlock(&mutex);

}
}

void* threadC(void* args) {
int i;
for(i=0; i<5; i++){

pthread_mutex_lock(&mutex);

while(state == 1 || state == 0) pthread_cond_wait(&cond,&mutex);

printf("Thread C\n\n");
state = (state+1)%num_threads;
pthread_cond_signal(&cond);

pthread_mutex_unlock(&mutex);

}
}


int main() {

pthread_t tid[3];

pthread_cond_init(&cond,NULL);
pthread_mutex_init(&mutex,NULL);

pthread_create(&tid[0],NULL,threadA,NULL);
pthread_create(&tid[1],NULL,threadB,NULL);
pthread_create(&tid[2],NULL,threadC,NULL);

return 0;
}

- abhidivster May 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

We also can use Thread priorities while running. One Thread will have MAX_PRIORITY, second one will have NORM_PRIORITY and Third one will have MIN_PRIORITY. In this way, Threads will execute sequentially.

- LeenaS July 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

We can use priority also. In this case since there are only 3 thread, we can assign priority using min_priority, Max_priority and norm_priority, therefore they will run in sequntial manner

- Anonymous August 15, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. If you know the exact sequence then simply invoke run method sequentially without creating Thread.
2. If you know the exact sequence and Threads have to be created in anyway then we can go for setting the priorities according to the sequence.
3. And if the sequence is not known and Threads have to be created then simply use synchronized block or lock method of ReentrantLock Class inside run() method.

- Anonymous February 06, 2018 | 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