Click here to Skip to main content
12,623,903 members (28,647 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: Java
I want to write product objects per consumer to a file based on region. This is the method:

protected static void writeRecordsToFiles(ProductConsumer[] consumers) {
 
        try {
            BufferedWriter[] bufferedWriters = {
                new BufferedWriter(new FileWriter("data/US_Timezones/central.txt")),
                new BufferedWriter(new FileWriter("data/US_Timezones/eastern.txt")), 
                new BufferedWriter(new FileWriter("data/US_Timezones/mountain.txt")),
                new BufferedWriter(new FileWriter("data/US_Timezones/pacific.txt"))
            };
 
            for (int i = 0; i < bufferedWriters.length; i++) {
                bufferedWriters[i].write(consumers[i].toString());
                bufferedWriters[i].newLine();
                bufferedWriters[i].flush();
 
                for (ProductProducer record : consumers[i].msgList.get()) {
                    bufferedWriters[i].write(record.toString());
                    bufferedWriters[i].newLine();
                    bufferedWriters[i].flush();
                }
                bufferedWriters[i].close();
            }
            
        } catch (IOException ex) {
            Logger.getLogger(Mp3Like1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

For this line:
for (ProductProducer record : consumers[i].msgList.get()) {

I get the error messages in Netbeans:
msgList has protected access in ProductConsumer
method get in interface List<e> cannot be applied to given types;
required: int
found: no arguments
reason: actual and formal argument lists differ in length
where E is a type-variable:
E extends Object declared in interface List

Here is the code from the whole class, and from the rest of the classes. Thank you in advance:

package mp3like1;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import parallelpatterns.ProductConsumer;
import parallelpatterns.ProductProducer;
 
public class Mp3Like1 {
 
    public static void main(String[] args) {
        
        long simStartTime = System.currentTimeMillis();
        System.out.println("Simulation started at 0 secs: " + simStartTime + "\n");
        
        // 2 Producer threads...
        ProductProducer producerOne = new ProductProducer("alaskan");
        new Thread(producerOne).start();
        ProductProducer producerTwo = new ProductProducer("hawaian");
        new Thread(producerTwo).start();
 
        // 4 Region Consumer threads....
        ProductConsumer consumer1 = new ProductConsumer("eastern", producerOne, producerTwo, 500L);
        Thread c1 = new Thread(consumer1);
        c1.setDaemon(true);
        c1.start();
        ProductConsumer consumer2 = new ProductConsumer("central", producerOne, producerTwo, 600L);
        Thread c2 = new Thread(consumer2);
        c2.setDaemon(true);
        c2.start();
        ProductConsumer consumer3 = new ProductConsumer("mountain", producerOne, producerTwo, 700L);
        Thread c3 = new Thread(consumer3);
        c3.setDaemon(true);
        c3.start();
        ProductConsumer consumer4 = new ProductConsumer("pacific", producerOne, producerTwo, 800L);
        Thread c4 = new Thread(consumer4);
        c4.setDaemon(true);
        c4.start();
 
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.println("Press a key to exit...");
            in.read();
            System.out.println("\nExiting....\n");
            in.close();
            System.out.println("\nTotal simulation runtime was: " + (System.currentTimeMillis() - simStartTime) * 1000.0 + " secs.");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            System.out.println("\nEastern Timezone's messages: \n" + consumer1 + "\n");
            System.out.println("\nCentral Timezone's messages: \n" + consumer2 + "\n");
            System.out.println("\nMountain Timezone's messages: \n" + consumer3 + "\n");
            System.out.println("\nPacific Timezone's messages: \n" + consumer4 + "\n");
            System.exit(0);
        }
    }
    
    protected static void writeRecordsToFiles(ProductConsumer[] consumers) {
 
        try {
            BufferedWriter[] bufferedWriters = {
                new BufferedWriter(new FileWriter("data/US_Timezones/central.txt")),
                new BufferedWriter(new FileWriter("data/US_Timezones/eastern.txt")), 
                new BufferedWriter(new FileWriter("data/US_Timezones/mountain.txt")),
                new BufferedWriter(new FileWriter("data/US_Timezones/pacific.txt"))
            };
 
            for (int i = 0; i < bufferedWriters.length; i++) {
                bufferedWriters[i].write(consumers[i].toString());
                bufferedWriters[i].newLine();
                bufferedWriters[i].flush();
 
                for (ProductProducer record : consumers[i].msgList.get()) {
                    bufferedWriters[i].write(record.toString());
                    bufferedWriters[i].newLine();
                    bufferedWriters[i].flush();
                }
                bufferedWriters[i].close();
            }
            
        } catch (IOException ex) {
            Logger.getLogger(Mp3Like1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
}
package domain;
 
//import java.util.logging.Logger;

public class Product {
    private String ProductID;
    private String ProductName;
    private String ProductDescription;
    private Double weight;
    private Double cost;
    //private static final Logger LOG = Logger.getLogger(Product.class.getName());

    public Product() {
        // Init instance variables...
    }
 
    public Product(String prd) {
 
    }
 
    public String getProductID() {
        return ProductID;
    }
 
    public void setProductID(String ProductID) {
        this.ProductID = ProductID;
    }
 
    public String getProductName() {
        return ProductName;
    }
 
    public void setProductName(String ProductName) {
        this.ProductName = ProductName;
    }
 
    public String getProductDescription() {
        return ProductDescription;
    }
 
    public void setProductDescription(String ProductDescription) {
        this.ProductDescription = ProductDescription;
    }
 
    public Double getWeight() {
        return weight;
    }
 
    public void setWeight(Double weight) {
        this.weight = weight;
    }
 
    public Double getCost() {
        return cost;
    }
 
    public void setCost(Double cost) {
        this.cost = cost;
    }
 
    public Product(String ProductID, String ProductName, String ProductDescription, Double weight, Double cost) {
        this.ProductID = ProductID;
        this.ProductName = ProductName;
        this.ProductDescription = ProductDescription;
        this.weight = weight;
        this.cost = cost;
    }
 
    @Override
    public String toString() {
        return "Product{" + "ProductID=" + ProductID + ", ProductName=" + ProductName + ", ProductDescription=" + ProductDescription + ", weight=" + weight + ", cost=" + cost + '}';
    }
 
}
 
package domain;
 
import java.util.Date;
 
public class ProductMessage {
    
    private Product product;
    private Date timeStamp;
    private String region;
 
    public ProductMessage(Product product, Date timeStamp, String region) {
        this.product = product;
        this.timeStamp = timeStamp;
        this.region = region;
    }
    
    public ProductMessage() {}
 
    public Product getProduct() {
        return product;
    }
 
    public void setProduct(Product product) {
        this.product = product;
    }
 
    public Date getTimeStamp() {
        return timeStamp;
    }
 
    public void setTimeStamp(Date timeStamp) {
        this.timeStamp = timeStamp;
    }
 
    public String getRegion() {
        return region;
    }
 
    public void setRegion(String region) {
        this.region = region;
    }
 
    @Override
    public String toString() {
        return "ProductMessage{" + "product=" + product + ", timeStamp=" + timeStamp + ", region=" + region + '}';
    }
   
}
 
package parallelpatterns;
 
//file: ProductConsumer.java

import domain.ProductMessage;
import java.util.ArrayList;
import java.util.List;
 
public class ProductConsumer implements Runnable {
    // There are four consumers; eastern, central, mountain, and pacific...

    private ProductProducer producerOne;
    private ProductProducer producerTwo;
    private String region;
    private long sleepInterval;
    protected List<ProductMessage> msgList;
 
    public ProductConsumer(String region, ProductProducer producerOne, 
            ProductProducer producerTwo, long sleepInterval) {
        this.producerOne = producerOne;
        this.producerTwo = producerTwo;
        this.region = region;
        this.sleepInterval = sleepInterval;
        msgList = new ArrayList<ProductMessage>();
    }
 
    public void run() {
        while (true) {
            checkProducerForMessage(producerOne);
            checkProducerForMessage(producerTwo);
        }
    }
    
    protected synchronized void checkProducerForMessage(ProductProducer prd) {
        ProductMessage message = prd.getMessage(region);       
        if (message != null) {
            msgList.add(message);
            System.out.println("Consumer: " + region + " region got message: \n" + 
                    message + "\nof total " + prd.getListSize() + " messages...");
        }
        try {
            Thread.sleep(sleepInterval);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public String toString() {
        String messageString = "";
        for (ProductMessage m : msgList) {
            messageString += m + "\n";
        }
        return messageString;
    }
}
package parallelpatterns;
 
import domain.Product;
import domain.ProductMessage;
import java.util.Date;
import java.util.Random;
 

public class ProductProducer implements Runnable {  
    
    private String prd;
    static final int MAXQUEUE = 5; 
    private java.util.List<ProductMessage> messageList;     
    /**
     *
     * @param prd
     */
    public ProductProducer(String prd){
      this.prd = prd;
      messageList = new java.util.ArrayList<ProductMessage>();
    }
 
    @Override
    public void run() {
        while (true) {
            putMessage();
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
            }
        }
    }
 
    private synchronized void putMessage() {
        while (messageList.size() >= MAXQUEUE) {
            try {
                wait(500L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        Random rnd = new Random();
        Product[] products = { 
            new Product("5A2C", "Widget", "The famous widget device (just a few are still available).",25.57, 99.99) , 
            new Product("7F5A", "WidgetPlusPlus", "Highly improved version of original Widget product.", 19.67, 149.49) 
        };
        rnd = new Random();
        Product rndPrd = products[rnd.nextInt(products.length)];              
        String[] regions = {"eastern", "central", "mountain", "pacific" };
        String rndReg = regions[rnd.nextInt(regions.length)];
        
        messageList.add(new ProductMessage(rndPrd, new Date(),rndReg)); 
        System.out.println("Producer: " + prd + " Queue: " + messageList.size() + " total at " + new Date());
        System.out.println("Producer: " + prd + " Queue: " + messageList.get(0).getRegion());
 
        notify();
    }
 
    // called by Consumer
    public synchronized ProductMessage getMessage(String region) {
        ProductMessage message = null;
        while (messageList.size() == 0) {
            try {
                notify();
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Consumer " + region + " checking region value from top element of queue: " + messageList.get(0).getRegion());
        if (region.equals(messageList.get(0).getRegion())) {
            return messageList.remove(0);
        }
        notify();
        return message;
    }
 
    public int getListSize() {
        return messageList.size();
    }
}
Posted 21-Dec-12 9:27am
100,001262

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Please be careful, you're mixing up there some things:

messageList in ProductProducer is a "native" List and only the constructor initializes it as an ArrayList. You need to make sure the specific constructor is called before using that list - or better make it an ArrayList right away.

Your loop
for (ProductProducer record : consumers[i].msgList.get()) {
  // some fun
}
also inculdes a false call. ArrayList.get() or List.get() does not exist - NetBeans should have told you so. Both need an int as argument.
Maybe you have a false import in there (some GUI component called "List" ?)

EDIT: Please also check out Richards Answer in the Java Forum here, he spotted also some primary problem (the above described will be visible when Richard's find is solved).
  Permalink  
v3
Comments
TorstenH. 22-Dec-12 5:32am
   
Also please - use getter and setters and do not make it all public. That's no good style.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web01 | 2.8.161128.1 | Last Updated 22 Dec 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100