United HealthGroup Interview Question
Java DevelopersCountry: India
Interview Type: Written Test
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.
Typical producer-consumer pattern. There are 2 ways to solve it. Either use a blocking queue or use a semaphore
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()
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);
}
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;
}
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.
// Main Method
- Sumit Kesarwani...... June 13, 2013package 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...:)