Edit: I have a producer class that send some data to the SharedBuffer class. This data is added to an ArrayList with the limit set to 100. There is no problem with adding data to said list, but the consumer class does not manage to get any of the data out of the list.
No output is produced at all (no null or errors).
Edit 2: The method for putting data inside the array was added.
SharedBuffer class:
static final int RESOURCE_LIMIT = 100;
private List<String> data = new ArrayList<String>();
// private boolean done = false;
public boolean isFull(){
return data.size() >= RESOURCE_LIMIT;
}
public boolean isEmpty(){
return data.size() <= 0;
}
public synchronized void putData(String s){
while(this.isFull()){
try{
wait();
}catch(InterruptedException e){
//
e.printStackTrace();
}
}
data.add(s);
//size works and there is data in list.
//System.out.println(data.size() + data.get(0));
public boolean isEmpty(){
return data.size() <= 0;
}
public synchronized String getData(){
while(this.isEmpty()){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
String s_data = (String)(data.get(0));
if(s_data != null){
data.remove(s_data);
System.out.println(s_data);
}
return s_data;
}
Consumer class:
@Override
public void run() {
while(true){
String line = buffer.getData();
if(line != null){
System.out.println(line);
//do stuff with the data.
}
}
}
Change your code (add notyfyAll()
invokation)
public synchronized void putData(String s){
while(this.isFull()){
try{
wait();
}catch(InterruptedException e){
//
e.printStackTrace();
}
}
data.add(s);
notifyAll();
}
public synchronized String getData(){
while(this.isEmpty()){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
String s_data = (String)(data.get(0));
if(s_data != null){
data.remove(s_data);
System.out.println(s_data);
}
notifyAll();
return s_data;
}
Also you should synchronize isEmpty
and isFull
methods because the access to data
.