United HealthGroup Interview Question for Java Developers


Country: India
Interview Type: Written Test




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

// Main Method


package com.sumit.Test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class PrducerConsumer {

/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
BlockingQueue<Integer> proConBlockingQueue = new ArrayBlockingQueue<Integer>(10);
Thread writerThread = new Thread(new Writer(proConBlockingQueue));
Thread readerThread = new Thread(new Reader(proConBlockingQueue));
writerThread.setName("Writing ");
readerThread.setName("Reading ");
writerThread.start();

readerThread.start();
}

}

//////// Writer Thread


package com.sumit.Test;

import java.util.concurrent.BlockingQueue;

public class Writer implements Runnable{


private final BlockingQueue<Integer> bQueue;

public Writer(BlockingQueue<Integer> bQueue)
{
this.bQueue = bQueue;
}


@Override
public void run() {
for(int i=0; i <10;i++)
{
try
{
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" : "+i);
bQueue.put(i);

}
catch(Exception ex)
{
ex.printStackTrace();
}
}

}

}


//// Reader Thread



package com.sumit.Test;

import java.util.concurrent.BlockingQueue;

public class Reader implements Runnable{


private final BlockingQueue<Integer> bQueue;
public Reader(BlockingQueue<Integer> bQueue)
{
this.bQueue = bQueue;
}
@Override
public void run() {
while(true)
{
try
{
System.out.println(Thread.currentThread().getName()+" : "+bQueue.take());
bQueue.take();
Thread.sleep(1000);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

}

}


Thanks Mrs. Seela...:)

- Sumit Kesarwani...... June 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Hey where you are removing element for writing purpose you adding
element in Blocking Queue but in reading queue you should remove element after printing,May be shumit you are doing same.

- Mystic June 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

No, I Checked It Its Working.... Sheela.

- Anonymous June 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 4 vote

Typical producer-consumer pattern. There are 2 ways to solve it. Either use a blocking queue or use a semaphore

- Murali Mohan June 12, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Why use a semaphore? BlockingQueue is correct!!

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

Its producer-consumer problem where writer should be treated as producer and reader as consumer, use either blocking queue method or wait-notify better to use blocking queue as wait-notify constraint will be taken care by this blocking queue API

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

Using Java provides thread API(s)

// reader writer manager through a buffer managed content
class ReaderWriter {

	// FIXED_BUFFER_SIZE value should be standard
	// so that performance is optimum
	// buffer has typically queue behavior
	private static final long FIXED_BUFFER_SIZE = <some standard numeric value>;
	
	// milliseconds idle interval
	// when no more data is avialable in buffer to read
	private static final long READER_IDLE_TIME = <milliseconds value>

	// thread safe
	StringBuffer buffer = new StringBuffer();
	
	/ /end flag
	AtomicBoolean end = new AtmoicBoolean(false);
	
	// reader thread
	class Reader implements Runnable {
	
		@Override
		public void run() {
			while(!end) {
				byte[] contents = buffer.read();
				// do something with contents
				if (contents.length == 0) {
					// content temporarily unavailable
					try {
						Thread.sleep(READER_IDLE_TIME);
					} catch(InterruptedException e) {
						throw new IllegalStateException(e.getMessage(), e);
					}
				}
			}
		}
	}

	// writer thread
	class Writer implements Runnable {
		
		@Override
		public void run() {
			while(!end) {
				// writes into buffer
				buffer.write(<get the content and write into>);
			}
		}
	}

	// reader writer thread
	Thread reader = new Thread(reader);
	Thread writer = new Thread(writer);
	
	void init() {
		// starts two theards
		reader.start();
		writer.start();
	}
	
	void feedBuffer(byte[] chunkOfBytes) {
		// copies into buffer
	}
	
	// destroy reader writer activity
	void destroy() {
		// destroy logic
		// sets end flag
		end.set(true);
		
		// if whole system has to stop
		// reader.join();
		// writer.join();
		// System.exit(0);
	}

}

ReaderWriter has to be used by some other program like .init() and .destroy()

- Debasis Jana June 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The first readers-writers problem[edit]

Suppose we have a shared memory area with the constraints detailed above. It is possible to protect the shared data behind a mutual exclusion mutex, in which case no two threads can access the data at the same time. However, this solution is suboptimal, because it is possible that a reader R1 might have the lock, and then another reader R2 requests access. It would be foolish for R2 to wait until R1 was done before starting its own read operation; instead, R2 should start right away. This is the motivation for the first readers-writers problem, in which the constraint is added that no reader shall be kept waiting if the share is currently opened for reading. This is also called readers-preference, with its solution below:
semaphore wrt=1,mutex=1;
readcount=0;
writer()
{
    wait(wrt);
    //writing is done
    signal(wrt);
}
 
reader()
{
    wait(mutex);
    readcount++;
    if(readcount==1)
        wait(wrt);
    signal(mutex);
    ///Do the Reading
    ///(Critical Section Area)
    wait(mutex);
    readcount--;
    if(readcount==0)
       signal(wrt);
    signal(mutex);
}

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

Here is a C++ program that demonstrates a solution to the producer-consumer problem using C++ 11 standard library threading support:

#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <deque>
using namespace std;

deque<int> _shared;
mutex _flag;
condition_variable _cond;

void produce() {
    while (true) {
        {
            cout << "tick" << endl;
            unique_lock<mutex> ul(_flag);
            if(_shared.size() <  10) {
                auto product = rand();
                _shared.push_back(product);
                cout << endl << "Produced " << product << endl;
            } else {
                _cond.wait(ul);
            }
        }
        this_thread::sleep_for(chrono::milliseconds(10));
    }
}
void consume() {
    while (true) {
        {
            unique_lock<mutex> ul(_flag);
            if(!_shared.empty()) {
                auto product = _shared.front();
                _shared.pop_front();
                cout << "Consumed " << product << endl;
                _cond.notify_one();
            }
            
        }
        this_thread::sleep_for(chrono::seconds(1));
        
    }
    
}


int main()
{
    thread p = thread(produce);
    thread c = thread(consume);
    
    p.join();
    c.join();
    return 0;
}

- Mhret November 25, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Construct two threads in a program and execute them one after another. Write thread writes the data in a buffer and reader thread reads the data of previous thread from the buffer. Before execution of threads, user has to provide the string of 10 words the writer thread reads data from the string and write one word in the buffer. The reader thread reads the word from the buffer and displays it on screen.

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

asdert n d da r esdrt dc l o k d tr reasdrt opij ui t r reasdrt iop u reasdrr ox

- Anonymous April 15, 2019 | 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