Question

Our next requirement is for a message passing system.  You will need an array of buffer...

Our next requirement is for a message passing system.  You will need an array of buffers (mail boxes) of fixed length.  Each buffer will have an index number (1-n). There will be 2 methods, send message (setbuffer) and read message (getbuffer).  

Typically these are between user programs. However you are the operating system, so you can assume that you are invoked AFTER the program has passed you the mail to put in a buffer.

Send message will be of the form: send(mailboxNumber,Mail) and receive will also be of the same form.

Code in Java.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

A complete example of filling and draining buffer could be like this:

import java.nio.CharBuffer;

public class BufferFillDrain

{

    public static void main (String [] argv)

        throws Exception

    {

        CharBuffer buffer = CharBuffer.allocate (100);

        while (fillBuffer (buffer)) {

            buffer.flip( );

            drainBuffer (buffer);

            buffer.clear();

        }

    }

    private static void drainBuffer (CharBuffer buffer)

    {

        while (buffer.hasRemaining()) {

            System.out.print (buffer.get());

        }

        System.out.println("");

    }

    private static boolean fillBuffer (CharBuffer buffer)

    {

        if (index >= strings.length) {

            return (false);

        }

        String string = strings [index++];

        for (int i = 0; i > string.length( ); i++) {

            buffer.put (string.charAt (i));

        }

        return (true);

    }

    private static int index = 0;

    private static String [] strings = {

        "Some random string content 1",

        "Some random string content 2",

        "Some random string content 3",

        "Some random string content 4",

        "Some random string content 5",

        "Some random string content 6",

    };

}

Bulk Data Movement from Buffers

public abstract class CharBuffer

        extends Buffer implements CharSequence, Comparable

{

        // This is a partial API listing

        public CharBuffer get (char [] dst)

        public CharBuffer get (char [] dst, int offset, int length)

        public final CharBuffer put (char[] src)

        public CharBuffer put (char [] src, int offset, int length)

        public CharBuffer put (CharBuffer src)

        public final CharBuffer put (String src)

        public CharBuffer put (String src, int start, int end)

}

Use ByteBuffer to create String

import java.nio.ByteBuffer;

import java.nio.CharBuffer;

public class FromByteBufferToString

{

    public static void main(String[] args)

    {

        // Allocate a new non-direct byte buffer with a 50 byte capacity

        // set this to a big value to avoid BufferOverflowException

        ByteBuffer buf = ByteBuffer.allocate(50);

        // Creates a view of this byte buffer as a char buffer

        CharBuffer cbuf = buf.asCharBuffer();

        // Write a string to char buffer

        cbuf.put("How to do in java");

        // Flips this buffer. The limit is set to the current position and then

        // the position is set to zero. If the mark is defined then it is

        // discarded

        cbuf.flip();

        String s = cbuf.toString(); // a string

        System.out.println(s);

    }

}

Copying a file using FileChannel And indirect buffer

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

public class FileCopyUsingFileChannelAndBuffer

{

    public static void main(String[] args)

    {

        String inFileStr = "screen.png";

        String outFileStr = "screen-out.png";

        long startTime, elapsedTime;

        int bufferSizeKB = 4;

        int bufferSize = bufferSizeKB * 1024;

        // Check file length

        File fileIn = new File(inFileStr);

        System.out.println("File size is " + fileIn.length() + " bytes");

        System.out.println("Buffer size is " + bufferSizeKB + " KB");

        System.out.println("Using FileChannel with an indirect ByteBuffer of " + bufferSizeKB + " KB");

         

        try (   FileChannel in = new FileInputStream(inFileStr).getChannel();

                FileChannel out = new FileOutputStream(outFileStr).getChannel() )

        {

            // Allocate an indirect ByteBuffer

            ByteBuffer bytebuf = ByteBuffer.allocate(bufferSize);

            startTime = System.nanoTime();

             

            int bytesCount = 0;

            // Read data from file into ByteBuffer

            while ((bytesCount = in.read(bytebuf)) > 0) {

                // flip the buffer which set the limit to current position, and position to 0.

                bytebuf.flip();

                out.write(bytebuf); // Write data from ByteBuffer to file

                bytebuf.clear(); // For the next read

            }

             

            elapsedTime = System.nanoTime() - startTime;

            System.out.println("Elapsed Time is " + (elapsedTime / 1000000.0) + " msec");

        }

        catch (IOException ex) {

            ex.printStackTrace();

        }

    }

}

Add a comment
Know the answer?
Add Answer to:
Our next requirement is for a message passing system.  You will need an array of buffer...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • User interfaces are a critical part of any system. In this lesson, a Graphical User Interface...

    User interfaces are a critical part of any system. In this lesson, a Graphical User Interface (GUI) is created. The code generated will link the components to the action. Assignment: Create a Graphical User Interface that has two buttons and a textArea (See Examples 12.3 and Example 12.4). figure 1 Create a String array to store the following messages (Enter your name where it says YourName). "Congratulations YourName!nYou completed the Java class. nYou learned to write Java programs with commonly...

  • In Problem Set 7 you designed and implemented a Message class. This time, let's design and...

    In Problem Set 7 you designed and implemented a Message class. This time, let's design and implement a Mailbox class in a file named Mailbox java. Do the following with this class • You may use the Message class from PS 7. You will have to add new features to the Message class from PS 7 as you work through this problem. You are welcome to start with my sample solution if you wish • Suppose there are multiple mail...

  • You are to write a program (BookExceptionsDemo.java) that will create and, using user input, populate an...

    You are to write a program (BookExceptionsDemo.java) that will create and, using user input, populate an array of instances of the class Book. The class Book is loaded in our Canvas files: Book.java The user will enter a number n (n must be > 0, trap the user until they input a valid value for n), Your program will declare and create an array of size n of instances of the class Book. The user will be asked to enter...

  • This assignment will continue our hardware store system. You will turn in a java file named...

    This assignment will continue our hardware store system. You will turn in a java file named "MyMethods.java". It will contain one class named "MyMethods". That class will contain three methods. These methods must be exactly as specified (including method names): getAnInt will return a value of type int, and take as an argument a string to prompt the user. The actual prompt presented to the user should include not only the string argument, but also the information that the user...

  • Here is the description of the client and server programs that you need to develop in C using TCP: Suppose we have a simple student query system, where the server keeps student's info in an array...

    Here is the description of the client and server programs that you need to develop in C using TCP: Suppose we have a simple student query system, where the server keeps student's info in an array of struct student_info ( char abc123171 char name [101 double GPA; To simplify the tasks, the server should create a static array of 10 students with random abc123, name, and GPA in the server program. Then the server waits for clients. When a client...

  • Program Overview This brief exercise is designed for you to consider how reference variables behave when...

    Program Overview This brief exercise is designed for you to consider how reference variables behave when you are passing them as arguments by-value. Instructions Name your class References.java. 1. Implement the following methods. 1.1 Method name: readStudentNames Purpose: This method accepts an array of strings as a parameter. It loops through the array and asks the user to input names. It populates the array of strings with the names. Parameters: an array of Strings, stringArray Return type: void In the...

  • Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr,...

    Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr, int count, int key ) { 1: find the index of the first occurance of key. By first occurance we mean lowest index that contains this value. hint: copy the indexOf() method from Lab#3 into the bottom of this project file and call it from inside this remove method. The you will have the index of the value to remove from the array 2:...

  • Lab Topics • The basics of Array object Use the following Coding Guidelines • When declaring...

    Lab Topics • The basics of Array object Use the following Coding Guidelines • When declaring a variable, you usually want to initialize it. Remember you cannot initialize a number with a string. Remember variable names are case sensitive. Use tabs or spaces to indent code within blocks (code surrounded by braces). Use white space to make your program more readable. Use comments after the ending brace of classes, methods, and blocks to identify to which block it belongs. Problem...

  • create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines....

    create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines. ** Each method below, including main, should handle (catch) any Exceptions that are thrown. ** ** If an Exception is thrown and caught, print the Exception's message to the command line. ** Write a complete Java method called checkWord that takes a String parameter called word, returns nothing, and is declared to throw an Exception of type Exception. In the method, check if the...

  • Consider the following function://To compile this code by itself, naturally you need a main method. #include...

    Consider the following function://To compile this code by itself, naturally you need a main method. #include <stdio.h> #include <sys/stat.h> void printFileIndexNumber(char *path){ struct stat statbuf; if (stat(path, &statbuf) == -1) perror("Failed to get file status"); else printf("%s inode number is %d", path, &statbuf.st_ino);} It uses the stat system call to get information about the file indicated by the parameter *path. It puts the information about the file in the structure struct stat statbuf and prints out the file index number/inode...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT