March 2nd, 2023

Free Starter Class, practicing with Streams on Eclipse IDE and Java 19

package main;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Stream;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		ArrayList<Integer> integerArrayList = new ArrayList<>(Arrays.asList(2,3,5,7,1,9,6,0,4));
		Stream<Integer> integerStream = integerArrayList.stream();
		
		integerStream.filter(n -> n > 5)
					 .sorted()
					 .map(n -> n*4)
					 .forEach((value) -> {				
			System.out.println(value);
		});
	}

}

Output

24
28
36

catching Exceptions, some exceptions can be non ideally upsold to all exceptions

Ram can be modified while in use

Protection far from guaranteed

System works in some directions can be non ideally upsold to works in all directions

Thoughts exception handling around Java NIO Bind is bloated

Throws:ConnectionPendingException - If a non-blocking connect operation is already in progress onthis channelAlreadyBoundException - If the socket is already boundUnsupportedAddressTypeException - If the type of the given address is not supportedClosedChannelException - If the channel is closedIOException - If some other I/O error occursSecurityException - If a security manager has been installed and its checkListen method deniesthe operation for an Internet protocol socket address,or for a Unix domain socket address if it denies "accessUnixDomainSocket").

Quite a few exceptions to handle for just trying to connect

Socket Channel is TCP and Datagram is UDP I think and Oppression limiting me far less than ideal

Following code from HeatByteBuffer is throwing an error

    public ByteBuffer get(byte[] dst, int offset, int length) {
        checkSession();
        Objects.checkFromIndexSize(offset, length, dst.length);
        int pos = position();
        if (length > limit() - pos)
            throw new BufferUnderflowException();
        System.arraycopy(hb, ix(pos), dst, offset, length);
        position(pos + length);
        return this;
    }

Special ByteBuffer for Java NIO instead of normal ByteArrayOutputStream?

	public static void connectClient() {
		try {
			
			SocketChannel clientChannel = NetworkUtil.createTCPClientSocket("127.0.0.1", 7777);
			
			final StringWriter stringWriter = new StringWriter();
			stringWriter.append("Message to send");
			
			byte bytes[] = stringWriter.toString().getBytes();
			ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
			buffer.put(bytes);
			byte destinationBytes[] = new byte[bytes.length];
			buffer.get(destinationBytes);
			String testString = new String(destinationBytes);			
			clientChannel.write(buffer);						
		} catch (IOException e) {
			logger.severe("Client Thread Exception: "+e.toString());
		}		
	}

The class appears broken, might be missing something.

Free Starter Java Classes

package main;

import java.io.IOException;
import java.io.StringWriter;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Logger;
import java.util.stream.Stream;

import network.NetworkUtil;

public class Main {
	private static Logger logger = Logger.getLogger(Main.class.toString());

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		ArrayList<Integer> integerArrayList = new ArrayList<>(Arrays.asList(2,3,5,7,1,9,6,0,4));
		Stream<Integer> integerStream = integerArrayList.stream();
		
		integerStream.filter(n -> n > 5)
					 .sorted()
					 .map(n -> n*4)
					 .forEach((value) -> {				
			System.out.println(value);
		});
	
		setupServer();
		
		connectClient();
		
	}
	
	public static void connectClient() {
		try {
			
			SocketChannel clientChannel = NetworkUtil.createTCPClientSocket("127.0.0.1", 7777);
			
			final StringWriter stringWriter = new StringWriter();
			stringWriter.append("Message to send\n");
			
			byte messageInBytes[] = stringWriter.toString().getBytes();
			
			clientChannel.socket().getOutputStream().write(messageInBytes);
			
			String shutdownMessage = "SHUTDOWN";
			clientChannel.socket().getOutputStream().write(shutdownMessage.getBytes());
			
		} catch (IOException e) {
			logger.severe("Client Thread Exception: "+e.toString());
		}		
	}
	
	public static void setupServer() {
		Thread serverThread = new Thread(new Runnable() {				
			@Override
			public void run() {			
				
				ServerSocketChannel tcpServer = null;					
				SocketChannel serverChannel = null;
				try {
					tcpServer = NetworkUtil.createTCPServerSocket(7777);					
					serverChannel = tcpServer.accept();
					
					boolean keepRunning = true;
					while (keepRunning) {
						int available = serverChannel.socket().getInputStream().available();
						
						if (available > 0) {
							byte bytesRead[] = new byte[available];
							serverChannel.socket().getInputStream().read(bytesRead);
							String messageRead = new String(bytesRead);
							logger.info("Message Read from Server Socket on port 7777: "+messageRead);
							
							if (messageRead.indexOf("SHUTDOWN")>-1) {
								keepRunning = false;
							}
						}
					}
				} catch (IOException e) {
					logger.severe("Server Thread Exception: "+e.toString());
				} finally {
					if (null!=tcpServer) {
						try {
							tcpServer.close();
						} catch (IOException e) {
							logger.severe("Error closing Server: "+e.getMessage());
						}
					}
				}
				
				logger.info("Exiting Server thread");
				
			}
		});
		serverThread.start();
	}
}
package network;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;


public class NetworkUtil {
	
	public static SocketChannel createTCPClientSocket(String address, int port) throws IOException {
		SocketAddress socketAddress = new InetSocketAddress(address, port);
		SocketChannel socketChannel = SocketChannel.open(socketAddress);
		
		return socketChannel;
	}
	
	public static ServerSocketChannel createTCPServerSocket(int port) throws IOException {
		ServerSocketChannel channel = SelectorProvider.provider().openServerSocketChannel();
		channel.bind(new InetSocketAddress(port));
		return channel;
	}
}

Output on Eclipse IDE

24
28
36
Mar 02, 2023 8:18:54 AM main.Main$1 run
INFO: Message Read from Server Socket on port 7777: Message to send
SHUTDOWN
Mar 02, 2023 8:18:54 AM main.Main$1 run
INFO: Exiting Server thread

Network Interface as Free Global Local Storage?

Buffer that can be read from at leisure?

Server like a good book or a scaled load balanced supercar?

byte array output input stream
byte array output input stream
byte array output input stream
byte array output input stream

abcde fghijk lmnop qrstu vwxyz
abcde fghijk lmnop qrstu vwxyz
abcde fghijk lmnop qrstu vwxyz
abcde fghijk lmnop qrstu vwxyz

Disclaimer: Working with Live Circuits and High Voltages can be fatal, please use safety while updating CPU Components

100 years from now how much a Samsung 980 PCIE be worth?

Foundational technology that speeds up the future, not always valued to level it should be

One day might be some 400MP per frame Video, will need some fast storage for that

23296 by 17472 potential for a lot of less interpolated key details, also potential for lens smudges to do more damage, better prepare in advance

I find the following code hard to implement with stream API

Free Code for Conversation and Use

package main;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Logger;

public class Main {
	private static Logger logger = Logger.getLogger(Main.class.toString());	

	public static void main(String[] args) {
		
		ConcurrentLinkedQueue<String> sharedQueue = new ConcurrentLinkedQueue<>();
		
		Runnable producerRunnable = () -> {
			int count = 0;
			while (true) {
				count++;
				sharedQueue.add("Producer Count "+count);
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					logger.info("Producer Sleep Interrupted: "+e.getMessage());
				}
			}
		};
		
		Runnable consumerRunnable = () -> {
			while (true) {
				String element;
				
				while (!sharedQueue.isEmpty()) {
					element = sharedQueue.poll();
					logger.info(element);
				}
				try {
					Thread.sleep(250);
				} catch (InterruptedException e) {
					logger.info("Producer Sleep Interrupted: "+e.getMessage());
				}
			}
		};
		
		Thread producer = new Thread(producerRunnable);
		Thread consumer = new Thread(consumerRunnable);
		
		producer.start();
		consumer.start();
	}
}

processing stream of sharedQueue doesn’t remove elements from the queue thus the stream() api is less useful. Not as straightforward as I would like

Updated with Multithreading Pool and Unique Identifiers on Threads

package main;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

public class Main {
	private static Logger logger = Logger.getLogger(Main.class.toString());	

	public static void main(String[] args) {
		
		ConcurrentLinkedQueue<String> sharedQueue = new ConcurrentLinkedQueue<>();
		AtomicInteger threadCount = new AtomicInteger();
		AtomicInteger consumerThreadCount = new AtomicInteger();
		
				
		Runnable producerRunnable = () -> {
			String producerId = "producer-"+threadCount.incrementAndGet();
			int count = 0;
			while (true) {
				count++;
				sharedQueue.add(producerId+" : "+count);
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					logger.info("Producer Sleep Interrupted: "+e.getMessage());
				}
			}
		};
		
		Runnable consumerRunnable = () -> {
			String consumerId = "consumer-"+consumerThreadCount.incrementAndGet();
			while (true) {
				String element;
				
				while (!sharedQueue.isEmpty()) {
					element = sharedQueue.poll();
					logger.info(consumerId+" | "+element);
				}
				try {
					Thread.sleep(250);
				} catch (InterruptedException e) {
					logger.info("Consumer Sleep Interrupted: "+e.getMessage());
				}
			}
		};
		
		Thread producer = new Thread(producerRunnable);
		Thread consumer = new Thread(consumerRunnable);
		
		BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(6);
		
		ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4, 8, 1000, TimeUnit.MILLISECONDS, workQueue);
		
		workQueue.add(producer);
		workQueue.add(producer);
		workQueue.add(producer);
		workQueue.add(producer);
		workQueue.add(consumer);
		workQueue.add(consumer);
		
		workQueue.stream().forEach((task) -> {
			threadPoolExecutor.submit(task);
		});
	}
}
Example Output from Eclipse IDE Console

INFO: consumer-2 | producer-2 : 38
Mar 02, 2023 9:37:48 AM main.Main lambda$1
INFO: consumer-1 | producer-3 : 39
Mar 02, 2023 9:37:48 AM main.Main lambda$1
INFO: consumer-2 | producer-1 : 39
Mar 02, 2023 9:37:48 AM main.Main lambda$1
INFO: consumer-2 | producer-2 : 39
Mar 02, 2023 9:37:48 AM main.Main lambda$1
INFO: consumer-2 | producer-1 : 40
Mar 02, 2023 9:37:48 AM main.Main lambda$1
INFO: consumer-1 | producer-4 : 39
Mar 02, 2023 9:37:48 AM main.Main lambda$1
INFO: consumer-2 | producer-4 : 40
Mar 02, 2023 9:37:48 AM main.Main lambda$1
INFO: consumer-1 | producer-2 : 40
Mar 02, 2023 9:37:48 AM main.Main lambda$1
INFO: consumer-2 | producer-3 : 40

Threads like all fingers except for Thumbs

four fingers all pulling across a surface can add useful work

Threads can increase Surface Area (using a similar not exact correlation here)

Published by techinfodebug

Flex and Java Developer, Christian, Art, Music, Video, and Vlogging

Leave a comment