m

 

$ less metest.pl
use strict;
use warnings;

my $find = “this”;
my $replace = “that”;
my $substr=’Here’;
my $file = ‘data.txt’;
open my $info, $file or die “Could not open $file: $!”;

while( my $line = <$info>) {
if (index($line, $substr) != -1) {
$line=~ s/$find/$replace/g;
print $line;
}
}

close $info;

 

 

$ less data.txt
Here it is the case-1 , this can be avoided.
Here it is the case-2 , this can be avoided
Here it is the case-3
it is the case-4:

 

 

oye

my $message = <<‘END_MESSAGE’;my $message = <<‘END_MESSAGE’;this is a message .Here it is the case-1 , This can be avoided.Here it is the case-2 , This can be avoided.it is the case-3 , This can be avoided.END_MESSAGE
if (index($string, $substring) != -1) {   print “‘$string’ contains ‘$substring’\n”;} print $message;

use strict;use warnings; my $substring=’this’;my $substring2=’that’;
my $filename = ‘data.txt’;if (open(my $fh, ‘<:encoding(UTF-8)’, $filename)) {  while (my $row = <$fh>) {    chomp $row; if (index($row, $substring) != -1) { my $newString = $old =~ s/$substring/$substring2/r;   print $newString;}  }} else {  warn “Could not open file ‘$filename’ $!”;}

run vs start java

Per StackOverflow

 

 

public class StartVSRun {public static void main(String[] args) { Me  me2=new Me(); Thread me=new Thread(me2); /* me.start(); me.start(); class java.lang.Thread Exception in thread “main” java.lang.IllegalThreadStateException at java.lang.Thread.start(Unknown Source) at StartVSRun.main(StartVSRun.java:9) Picked up _JAVA_OPTIONS: -Xmx512M*/ me.run(); me.run(); System.out.println(“—————“); me.start(); //me.start(); //me.start(); //me.start();
}}
class Me implements Runnable{
@Override public void run() { System.out.println(Thread.currentThread().getName()); } }

main
main
—————
Thread-0
Picked up _JAVA_OPTIONS: -Xmx512M

 

The difference is that Thread.start() starts a thread, while Runnable.run() just calls a method.

Here run() always results in main ,start will gives thread-0,thread-1 etc.

 

up vote202down voteaccepted

First example: No multiple threads. Both execute in single (existing) thread. No thread creation.

R1 r1 = new R1();
R2 r2 = new R2();

r1 and r2 are just two different objects of the class that implements the Runnable interfaces which have that run() method. When you call r1.run() you are executing it in the current thread.

Second example: Two separate threads.

Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);

t1 and t2 are the objects of the class Thread. When you call t1.start(), it starts a new thread and calls the run() method of r1 internally to execute it within that new thread.

Log4j Refer

 

 

DEBUG is the lowest restricted java logging level and we should write everything we need to debug an application, this java logging mode should only be used on Development and Testing environment and must not be used in production environment.

INFO is more restricted than DEBUG java logging level and we should log messages which are informative purpose like Server has been started, Incoming messages, outgoing messages etc in INFO level logging in java.

WARN is more restricted than INFO java logging level and used to log warning sort of messages e.g. Connection lost between client and server. Database connection lost, Socket reaching to its limit. These messages and java logging level are almost important because you can setup alert on these logging messages in java and let your support team monitor health of your java application and react on this warning messages. In Summary WARN level is used to log warning message for logging in Java.

ERROR is the more restricted java logging level than WARN and used to log Errors and Exception, you can also setup alert on this java logging level and alert monitoring team to react on this messages. ERROR is serious for logging in Java and you should always print it.

FATAL java logging level designates very severe error events that will presumably lead the application to abort. After this mostly your application crashes and stopped.

OFF java logging level has the highest possible rank and is intended to turn off logging in Java.

 

 

 

 

https://logging.apache.org/log4j/2.0/manual/architecture.html

 

 

 

here is the log4j.xml file:

<?xml version=”1.0″ encoding=”UTF-8″ ?>

<!DOCTYPE log4j:configuration SYSTEM “log4j.dtd”>

<log4j:configuration xmlns:log4j=’http://jakarta.apache.org/log4j/’&gt;

 

 

<!– ============================== –>

<!– Append messages to the console –>

<!– ============================== –>

 

 

<appender name=”console” class=”org.apache.log4j.ConsoleAppender”>

<param name=”Target” value=”System.out” />

 

<layout class=”org.apache.log4j.PatternLayout”>

<!– The default pattern: Date Priority [Category] Message\n –>

<param name=”ConversionPattern” value=”[AC – %5p] [%d{ISO8601}] [%t] [%c{1} – %L] %m%n” />

</layout>

</appender>

 

<appender name=”logfile” class=”org.apache.log4j.RollingFileAppender”>

<param name=”File” value=”./logs/server.log” />

<param name=”MaxFileSize” value=”1000KB” />

<param name=”MaxBackupIndex” value=”2″ />

<layout class=”org.apache.log4j.PatternLayout”>

<param name=”ConversionPattern” value=”[AC – %-5p] {%d{dd.MM.yyyy – HH.mm.ss}} %m%n” />

</layout>

</appender>

 

<appender name=”payloadAppender” class=”org.apache.log4j.RollingFileAppender”>

<param name=”File” value=”./logs/payload.log” />

<param name=”MaxFileSize” value=”1000KB” />

<param name=”MaxBackupIndex” value=”10″ />

<layout class=”org.apache.log4j.PatternLayout”>

<param name=”ConversionPattern” value=”[AC – %-5p] {%d{dd.MM.yyyy – HH.mm.ss}} %m%n” />

</layout>

</appender>

 

<appender name=”errorLog” class=”org.apache.log4j.RollingFileAppender”>

<param name=”File” value=”./logs/error.log” />

<param name=”MaxFileSize” value=”1000KB” />

<param name=”MaxBackupIndex” value=”10″ />

<layout class=”org.apache.log4j.PatternLayout”>

<param name=”ConversionPattern” value=”[AC – %-5p] {%d{dd.MM.yyyy – HH.mm.ss}} %m%n” />

</layout>

</appender>

 

<appender name=”traceLog”

class=”org.apache.log4j.RollingFileAppender”>

<param name=”File” value=”./logs/trace.log” />

<param name=”MaxFileSize” value=”1000KB” />

<param name=”MaxBackupIndex” value=”20″ />

 

<layout class=”org.apache.log4j.PatternLayout”>

<param name=”ConversionPattern”

value=”[AccessControl – %-5p] {%t: %d{dd.MM.yyyy – HH.mm.ss,SSS}} %m%n” />

</layout>

</appender>

 

<appender name=”traceSocketAppender” class=”org.apache.log4j.net.SocketAppender”>

<param name=”remoteHost” value=”localhost” />

<param name=”port” value=”4445″ />

<param name=”locationInfo” value=”true” />

</appender>

 

<logger name=”TraceLogger”>

<level value=”trace” /> <!– Set level to trace to activate tracing –>

<appender-ref ref=”traceLog” />

</logger>

 

<logger name=”org.springframework.ws.server.endpoint.interceptor”>

<level value=”DEBUG” />

<appender-ref ref=”payloadAppender” />

</logger>

 

<root>

<level value=”error” />

<appender-ref ref=”errorLog” />

</root>

 

</log4j:configuration>

 

 

 

 

 

up vote64down vote The root logger resides at the top of the logger hierarchy. It is exceptional in three ways:

·         it always exists,

·         its level cannot be set to null

·         it cannot be retrieved by name.

The rootLogger is the father of all appenders. Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy (including rootLogger)

For example, if the console appender is added to the root logger, then all enabled logging requests will at least print on the console. If in addition a file appender is added to a logger, say L, then enabled logging requests for L and L’s children will print on a file and on the console. It is possible to override this default behavior so that appender accumulation is no longer additive by setting the additivity flag to false.

From the log4j manual

To sum up:

If you want not to propagate a logging event to the parents loggers (say rootLogger) then add the additivity flag to false in those loggers. In your case:

<logger name=”org.springframework.ws.server.endpoint.interceptor”

additivity=”false”>

<level value=”DEBUG” />

<appender-ref ref=”payloadAppender” />

</logger>

In standard log4j config style (which I prefer to XML):

log4j.logger.org.springframework.ws.server.endpoint.interceptor = INFO, payloadAppender

log4j.additivity.org.springframework.ws.server.endpoint.interceptor = false

Hope this helps.

 

 

http://stackoverflow.com/questions/1839647/how-to-configure-log4j-to-log-different-log-levels-to-different-files-for-the-sa?rq=1

 

up vote54down voteaccepted What you need to do is have a single <logger> definition with a defined level of INFO, but in your two appender definitions, you set their thresholds accordingly, e.g.

<appender name=”ERROR_FILE”>

<param name=”Threshold” value=”ERROR”/>

</appender>

 

<appender name=”GENERAL”>

<param name=”Threshold” value=”INFO”/>

</appender>

You then add both appenders to your logger:

<logger name=”com.acme”>

<level value=”INFO”/>

<appender-ref ref=”ERROR_FILE”/>

<appender-ref ref=”GENERAL”/>

</logger>

Log entries now going to the logger will get sent to both appenders, but since they have different independent thresholds, the ERROR_FILE appender will only log ERROR and above.

 

 

 
Full working solution including the date in the filename:

<appender name=”InfoFileAppender” class=”org.apache.log4j.rolling.RollingFileAppender”>

<rollingPolicy class=”org.apache.log4j.rolling.TimeBasedRollingPolicy”>

<param name=”FileNamePattern” value=”/var/output/Info_%d{ddMMyyyy}.log” />

</rollingPolicy>

<layout class=”org.apache.log4j.PatternLayout”>

<param name=”ConversionPattern” value=”%d{HH:mm:ss} %-5p %t %c{2} – %m%n” />

</layout>

<filter class=”org.apache.log4j.varia.LevelRangeFilter”>

<param name=”levelMin” value=”INFO” />

<param name=”levelMax” value=”INFO” />

</filter>

</appender>

 

<appender name=”ErrorFileAppender” class=”org.apache.log4j.rolling.RollingFileAppender”>

<param name=”Threshold” value=”ERROR” />

<rollingPolicy class=”org.apache.log4j.rolling.TimeBasedRollingPolicy”>

<param name=”FileNamePattern” value=”/var/output/Error_%d{ddMMyyyy}.log” />

</rollingPolicy>

<layout class=”org.apache.log4j.PatternLayout”>

<param name=”ConversionPattern” value=”%d{HH:mm:ss} %-5p %t %c{2} – %m%n” />

</layout>

</appender>

<root>

<level value=”INFO” />

<appender-ref ref=”InfoFileAppender” />

<appender-ref ref=”ErrorFileAppender” />

</root>

 

 

 

http://stackoverflow.com/questions/31840/java-logging-vs-log4j?rq=1

94down vote I’d say you’re probably fine with util.logging for the needs you describe.

For a good decision tree, have a look at Log4j vs java.util.logging

Question One : Do you anticipate a need for any of the clever handlers that Log4j has that JUL does not have, such as the SMTPHandler, NTEventLogHandler, or any of the very convenient FileHandlers?

Question Two : Do you see yourself wanting to frequently switch the format of your logging output? Will you need an easy, flexible way to do so? In other words, do you need Log4j’s PatternLayout?

Question Three : Do you anticipate a definite need for the ability to change complex logging configurations in your applications, after they are compiled and deployed in a production environment? Does your configuration sound something like, “Severe messages from this class get sent via e-mail to the support guy; severe messages from a subset of classes get logged to a syslog deamon on our server; warning messages from another subset of classes get logged to a file on network drive A; and then all messages from everywhere get logged to a file on network drive B”? And do you see yourself tweaking it every couple of days?

If you can answer yes to any of the above questions, go with Log4j. If you answer a definite no to all of them, JUL will be more than adequate and it’s conveniently already included in the SDK.

That said, pretty much every project these days seems to wind up including log4j, if only because some other library uses it.

 

Log4j has been around for a long time, and it works very well. I have no scientific study to back it, but based on what I’ve seen at a large number of clients, it is easily the logging framework that I see used more than any other. It has been around for a long time, and not been replaced by the Next Big Logging Framework, which says something.

It is dead simple to set up, and easy to learn the basic appenders (outputs). There are a whole host appenders that are available, including:

  1. ConsoleAppender
  2. DailyRollingFileAppender
  3. ExternallyRolledFileAppender
  4. FileAppender
  5. JDBCAppender
  6. JMSAppender
  7. NTEventLogAppender
  8. RollingFileAppender
  9. SMTPAppender
  10. SocketAppender
  11. SyslogAppender
  12. TelnetAppender
  13. WriterAppender

Plus others. It isn’t difficult to write your own appender either. Additionally there is a great deal of flexibility in each of the appenders that allow you to control specifically what is output in your log.

One note, I had a series of classloader problems when I used apache commons logging in addition to log4j. It was only for one specific application, but I found it simpler to use log4j alone, rather than to have the flexibility offered when using an abstraction layer like commons logging.

See this article for more details:

Good luck!

 

 

http://stackoverflow.com/questions/4598702/dynamically-changing-log4j-log-level?rq=1

58down voteaccepted Changing the log level is simple; modifying other portions of the configuration will pose a more in depth approach.

LogManager.getRootLogger().setLevel(Level.DEBUG);The changes are permanent through the life cyle of the Logger. On reinitialization the configuration will be read and used as setting the level at runtime does not persist the level change.

UPDATE: If you are using Log4j 2 you should remove the calls to setLevel per the documentation as this can be achieved via implementation classes.

Calls to logger.setLevel() or similar methods are not supported in the API. Applications should remove these. Equivalent functionality is provided in the Log4j 2 implementation classes but may leave the application susceptible to changes in Log4j 2 internals.

 

 

http://stackoverflow.com/questions/8965946/configuring-log4j-loggers-programmatically?rq=1

216down voteaccepted You can add/remove Appender programmatically to Log4j:

ConsoleAppender console = new ConsoleAppender(); //create appender  //configure the appender  String PATTERN = “%d [%p|%c|%C{1}] %m%n”;  console.setLayout(new PatternLayout(PATTERN));   console.setThreshold(Level.FATAL);  console.activateOptions();  //add appender to any Logger (here is root)  Logger.getRootLogger().addAppender(console);   FileAppender fa = new FileAppender();  fa.setName(“FileLogger”);  fa.setFile(“mylog.log”);  fa.setLayout(new PatternLayout(“%d %-5p [%c{1}] %m%n”));  fa.setThreshold(Level.DEBUG);  fa.setAppend(true);  fa.activateOptions();   //add appender to any Logger (here is root)  Logger.getRootLogger().addAppender(fa);  //repeat with all other desired appendersI’d suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with

Logger.getRootLogger().getLoggerRepository().resetConfiguration();and start with adding your own. You need log4j in the classpath of course for this to work.

Remark:
You can take any Logger.getLogger(…) you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).

If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:

Logger fizz = LoggerFactory.getLogger(“com.fizz”)will give you a logger for the category “com.fizz”.
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to Logger.getLogger(“com.fizz”).addAppender(newAppender) then logging from fizz will be handled by alle the appenders from the root logger and the newAppender.
You don’t create Loggers with the configuration, you just provide handlers for all possible categories in your system.

 

 

http://stackoverflow.com/questions/1666121/programmatically-creating-different-log-files-using-log4j?noredirect=1&lq=1

up vote22down voteaccepted You can easily invoke log4j’s API programmatically, e.g.

FileAppender appender = new FileAppender();

// configure the appender here, with file location, etc

appender.activateOptions();

 

Logger logger = getRootLogger();

logger.addAppender(appender);

The logger can be the root logger as in this example, or any logger down the tree. Your unit test can add its custom appender during steup, and remove the appender (using removeAppender()) during teardown.

 

 

 

http://stackoverflow.com/questions/39169388/log4j-logging-twice-with-different-formats?noredirect=1&lq=1

 

 

http://stackoverflow.com/questions/728295/creating-multiple-log-files-of-different-content-with-log4j?rq=1

up vote69down vote This should get you started:

log4j.rootLogger=QuietAppender, LoudAppender, TRACE

# setup A1

log4j.appender.QuietAppender=org.apache.log4j.RollingFileAppender

log4j.appender.QuietAppender.Threshold=INFO

log4j.appender.QuietAppender.File=quiet.log

 

 

# setup A2

log4j.appender.LoudAppender=org.apache.log4j.RollingFileAppender

log4j.appender.LoudAppender.Threshold=DEBUG

log4j.appender.LoudAppender.File=loud.log

 

log4j.logger.com.yourpackage.yourclazz=TRACE

 

http://stackoverflow.com/questions/2763740/log4j-log-output-of-a-specific-class-to-a-specific-appender?rq=1

log4j.rootLogger=ERROR, logfile

 

log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender

log4j.appender.logfile.datePattern=’-‘dd’.log’

log4j.appender.logfile.File=log/radius-prod.log

log4j.appender.logfile.layout=org.apache.log4j.PatternLayout

log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x – %m\n

 

log4j.logger.foo.bar.Baz=DEBUG, myappender

log4j.additivity.foo.bar.Baz=false

 

log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender

log4j.appender.myappender.datePattern=’-‘dd’.log’

log4j.appender.myappender.File=log/access-ext-dmz-prod.log

log4j.appender.myappender.layout=org.apache.log4j.PatternLayout

log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x – %m\n

 

 

http://stackoverflow.com/questions/3687384/log4j-redirection-to-desktop-application-in-swing?rq=1

up vote4down voteaccepted The simplest option is to programmatically add your appender once your GUI has been initialised. Something like this:

Logger.getRootLogger().addAppender(yourTextAreaAppender);EDIT: To only log the INFO level do this:

yourTextAreaAppender.addFilter(new Filter() {    @Override    public int decide(LoggingEvent event) {        if (event.getLevel().equals(Level.INFO)) {            return ACCEPT;        } else {            return DENY;        }    }});

shareimprove this answer

 

http://stackoverflow.com/questions/1207889/log4j-rerouting-of-log-events?rq=1

 

ScheduledThreadPool in JAVA

A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required.

Delayed tasks execute no sooner than they are enabled, but without any real-time guarantees about when, after they are enabled, they will commence. Tasks scheduled for exactly the same execution time are enabled in first-in-first-out (FIFO) order of submission.

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

Timer VS ScheduledThreadPool

223down voteaccepted

According to Java Concurrency in Practice:

  • Timer can be sensitive to changes in the system clock, ScheduledThreadPoolExecutor isn’t.
  • Timer has only one execution thread, so long-running task can delay other tasks. ScheduledThreadPoolExecutor can be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providing ThreadFactory).
  • Runtime exceptions thrown in TimerTask kill that one thread, thus making Timer dead 😦 … i.e. scheduled tasks will not run anymore. ScheduledThreadExecutor not only catches runtime exceptions, but it lets you handle them if you want (by overriding afterExecute method from ThreadPoolExecutor). Task which threw exception will be canceled, but other tasks will continue to run.

If you can use ScheduledThreadExecutor instead of Timer, do so.

 

ScheduledExecutorService scheduledExecutorService=
Executors.newScheduledThreadPool(10);

for(int i=0;i<10;i++){
Thread_Creation creation=new Thread_Creation(“meeee”);
scheduledExecutorService.schedule(creation, 10, TimeUnit.SECONDS);
//Wiil do parallelly
}

Note that all the schedule() methods return instance of ScheduledFuture that we can use to get the thread state information and delay time for the thread.

ScheduledFuture extends Future interface, read more about them at Java Callable Future Example.

There are two more methods in ScheduledExecutorService that provide option to schedule a task to run periodically.

 

http://www.journaldev.com/2340/java-scheduler-scheduledexecutorservice-scheduledthreadpoolexecutor-example

 

Timer and TimerTask -Execute a task for every 5 seconds in JAVA

https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html

https://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html

 

package com.practice.thread;

import java.util.Timer;
import java.util.TimerTask;

public class TimerClass extends TimerTask{

@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(“——–START———–“);
SomeWork();
System.out.println(“————–END——–“);
}

private void SomeWork() {
System.out.println(“INSIDE LOGIC PROGERSSSSSS”);
}

public static void main(String[] args) {
TimerClass timerTask=new TimerClass();
//have cancel() ,run() and scheduledExecutionTime() to know the time of task execution

Timer timer=new Timer();
//Run as daemon thred,By default thread is not daemon
//uses FIFO
//By default it is Thread-safe
//It uses Object.wait(long) to schedule .

//timer.schedule(timerTask, 1000,5000);

timer.scheduleAtFixedRate(timerTask, 0, 5000);
//Schedules the specified task for execution at the specified time.
//If the time is in the past, the task is scheduled for immediate execution.

//timer.cancel();

}

}

 

——–START———–
INSIDE LOGIC PROGERSSSSSS
————–END——–
——–START———–
INSIDE LOGIC PROGERSSSSSS
————–END——–
——–START———–
INSIDE LOGIC PROGERSSSSSS
————–END——–
——–START———–
INSIDE LOGIC PROGERSSSSSS
————–END——–
——–START———–
INSIDE LOGIC PROGERSSSSSS
————–END——–
——–START———–
INSIDE LOGIC PROGERSSSSSS
————–END——–

…………………………….

…………….continues………………….

ThreadPoolExecutor(C) in JAVA

  • ThreadPoolExecutor class used for executing a group of threads by using the Executors(I) factory methods.
  • It is a known implementation of Executor(I),ExecutorService(I) and it allows callble or runnable objects as params.
  • It creates the thread objects and executes it and destirys it by using of varoius methods in ThreadPoolExecutor class.

Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.

  • getcurrentPoolSize() ==> gives current pool elemnts size
  • getCorepoolSize()     ====> Intial size i.e no of Queue elemnts.
  • getMaxPoolSize()     =====> Large size  i.e MAX elements.
  • When the new task is submitted to execute() and less than getCuurentSize()   a new thread is created.
  • if more than coresize and less than max size then a thread created in the queue(synchronus queue,LinkedBlockingqueu,ArrayblockingQueue).

A detailed desc is below.

 

Source:

package com.practice.thread;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Thread_Creation implements Runnable{

public String stringThread=null;

public Thread_Creation(String stringThread) {
super();
this.stringThread = stringThread;
}

public String getStringThread() {
return stringThread;
}

public void setStringThread(String stringThread) {
this.stringThread = stringThread;
}

@Override
public String toString() {
// TODO Auto-generated method stub
return this.stringThread.toString();
}

@Override
public void run() {
// TODO Auto-generated method stub
// default-method in runnable(I)

System.out.println(“Start”);
System.out.println(Thread.currentThread().getName()+stringThread);
logicMethod();
System.out.println(“stop”);
System.out.println(Thread.currentThread().getName()+stringThread);

}

private void logicMethod() {
// TODO Auto-generated method stub
//We are simply sleep it for 5 sec.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

public class Simple_Thread{
public static void main(String[] args) {
Runnable runnable=null;
ExecutorService executorService=Executors.newFixedThreadPool(5);
//It will creates the new threads of 15.
//One dis-advantage is if num is big it get overloaded.

for(int i=0;i<10;i++){
runnable=new Thread_Creation(” “+i);
executorService.execute(runnable);
}
}
}

 

Start
Start
Start
Start
pool-1-thread-1 0
Start
pool-1-thread-3 2
pool-1-thread-5 4
pool-1-thread-2 1
pool-1-thread-4 3
stop
stop
stop
stop
pool-1-thread-3 2
stop
pool-1-thread-5 4
Start
pool-1-thread-3 5
Start
pool-1-thread-5 6
pool-1-thread-2 1
pool-1-thread-4 3
pool-1-thread-1 0
Start
Start
pool-1-thread-4 8
Start
pool-1-thread-2 7
pool-1-thread-1 9
stop
stop
pool-1-thread-5 6
pool-1-thread-3 5
stop
pool-1-thread-1 9
stop
pool-1-thread-2 7
stop
pool-1-thread-4 8

 

package com.practice.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class Rejected_Threads implements RejectedExecutionHandler{

@Override
public void rejectedExecution(Runnable runnable, ThreadPoolExecutor arg1) {
// TODO Auto-generated method stub
System.out.println(runnable+”got rejected:”);
}

}

class Mainlogic_Thread implements Runnable{

public ThreadPoolExecutor executor;
public boolean run=true;
public int seconds;

public Mainlogic_Thread(ThreadPoolExecutor threadpoolObject, int seconds) {
super();
this.executor = threadpoolObject;
this.seconds = seconds;
}

public void shutdown(){
this.run=false;
}

@Override
public void run() {
// TODO Auto-generated method stub
while(run){
System.out.println(
String.format(“[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s”,
this.executor.getPoolSize(),
this.executor.getCorePoolSize(),
this.executor.getActiveCount(),
this.executor.getCompletedTaskCount(),
this.executor.getTaskCount(),
this.executor.isShutdown(),
this.executor.isTerminated()));
try {
Thread.sleep(seconds*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}
public class Thread_pool_executer {
public static void main(String[] args) throws InterruptedException {
Rejected_Threads rejected_Threads=new Rejected_Threads();
ThreadFactory threadFactory=Executors.defaultThreadFactory();
ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(2, 4, 10,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(2),threadFactory,rejected_Threads);

//Notice that while initializing the ThreadPoolExecutor, we are keeping initial pool
//size as 2, maximum pool size to 4 and work queue size as 2. So if there are 4
//running tasks and more tasks are submitted, the work queue will hold only 2 of
//them and rest of them will be handled by RejectedExecutionHandlerImpl.

Mainlogic_Thread mainlogic_Thread=new Mainlogic_Thread(threadPoolExecutor, 3);
Thread thread=new Thread(mainlogic_Thread);
thread.start();

for(int i=0; i<10; i++){
threadPoolExecutor.execute(new Thread_Creation(“cmd”+i));
}

System.out.println(threadPoolExecutor.getCorePoolSize());
System.out.println(threadPoolExecutor.getMaximumPoolSize());

Thread.sleep(30000);
//shut down the pool
threadPoolExecutor.shutdown();
//It won’t execute any pending taks if we call shutdown()
//shut down the monitor thread
//If shout down is called it goes to rejection if we try to put it in executor queue
threadPoolExecutor.execute(new Thread_Creation(“nene”+2));
Thread.sleep(5000);
mainlogic_Thread.shutdown();

}
}

 

Start
cmd6got rejected:
pool-1-thread-1cmd0
cmd7got rejected:
Start
cmd8got rejected:
pool-1-thread-2cmd1
cmd9got rejected:
2
4
Start
pool-1-thread-3cmd4
Start
pool-1-thread-4cmd5
[monitor] [0/2] Active: 0, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
stop
stop
pool-1-thread-2cmd1
pool-1-thread-1cmd0
Start
pool-1-thread-2cmd2
Start
pool-1-thread-1cmd3
stop
stop
pool-1-thread-3cmd4
pool-1-thread-4cmd5
stop
stop
pool-1-thread-1cmd3
pool-1-thread-2cmd2
[monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
nene2got rejected:
[monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true
[monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true

ThreadFactory(I) in JAVA

Here are some notes on ThreadFactory(I):

A Sample Programme:

package com.practice.thread;

import java.awt.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.concurrent.ThreadFactory;

class LogicThread implements Runnable{

@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}

}

class ThreadFactoryImpl implements ThreadFactory{
private String threadName;
public ThreadFactoryImpl(String threadName) {
super();
this.threadName = threadName;
this.listThreads = new ArrayList<String>();
}
private int counter=1;
private java.util.List<String> listThreads;

@Override
public Thread newThread(Runnable r) {
// TODO Auto-generated method stub
Thread t = new Thread(r, threadName + “-Thread_” + counter);
counter++;
listThreads.add(String.format(“Created thread %d with name %s on %s \n”, t.getId(), t.getName(), new Date()));
return t;
}

public String getThreadValues(){
StringBuffer stringBuffer=new StringBuffer();
Iterator<String> iterator=listThreads.iterator();
while(iterator.hasNext()){
stringBuffer.append(iterator.next());
}
return stringBuffer.toString();
}
}
public class ThreadFactoryExample {
public static void main(String[] args) {
ThreadFactoryImpl threadFactoryImpl=new ThreadFactoryImpl(“Thread_Factory”);
LogicThread logicThread=new LogicThread();
//Thread logic i.e sleep
Thread thread;
for(int i=0;i<10;i++){
thread=new Thread(logicThread);
thread=threadFactoryImpl.newThread(thread);
//Creating thread using Facoty Impl by using newThread()
thread.start();
}
System.out.println(threadFactoryImpl.getThreadValues());
}
}

 

Created thread 11 with name Thread_Factory-Thread_1 on Sun Jan 22 14:24:17 IST 2017
Created thread 13 with name Thread_Factory-Thread_2 on Sun Jan 22 14:24:17 IST 2017
Created thread 15 with name Thread_Factory-Thread_3 on Sun Jan 22 14:24:17 IST 2017
Created thread 17 with name Thread_Factory-Thread_4 on Sun Jan 22 14:24:17 IST 2017
Created thread 19 with name Thread_Factory-Thread_5 on Sun Jan 22 14:24:17 IST 2017
Created thread 21 with name Thread_Factory-Thread_6 on Sun Jan 22 14:24:17 IST 2017
Created thread 23 with name Thread_Factory-Thread_7 on Sun Jan 22 14:24:17 IST 2017
Created thread 25 with name Thread_Factory-Thread_8 on Sun Jan 22 14:24:17 IST 2017
Created thread 27 with name Thread_Factory-Thread_9 on Sun Jan 22 14:24:17 IST 2017
Created thread 29 with name Thread_Factory-Thread_10 on Sun Jan 22 14:24:17 IST 2017

Thread_Factory-Thread_1
Thread_Factory-Thread_3
Thread_Factory-Thread_2
Thread_Factory-Thread_4
Thread_Factory-Thread_9
Thread_Factory-Thread_5
Thread_Factory-Thread_6
Thread_Factory-Thread_7
Thread_Factory-Thread_8
Thread_Factory-Thread_10

 

Static vs Normal vs No imports in JAVA

Why imports are useful:

An import declaration allows a static member or a named type to be referred to by a simple name that consists of a single identifier. Without the use of an appropriate import declaration, the only way to refer to a type declared in another package, or a static member of another type, is to use a fully qualified name.

A single-type-import declaration imports a single named type, by mentioning its canonical name.

A type-import-on-demand declaration imports all the accessible types of a named type or package as needed. It is a compile time error to import a type from the unnamed package.

A single static import declaration imports all accessible static members with a given name from a type, by giving its canonical name.

A static-import-on-demand declaration imports all accessible static members of a named type as needed.

http://stackoverflow.com/questions/2903166/meaning-of-the-import-statement-in-a-java-file

What happen if we don’t declare imports in JAVA file:

The below program I am trying to call one of the method add of Arraylist i.e java.util.Arraylist i.e https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add(E) .As i didn’t declared any imports in my .java file it throws error like below.

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
Arraylist arraylist=new Arraylist();
System.out.println(arraylist.add());
}
}

o/p:
D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java
StaticVsNormalVsNo_Imports.java:4: error: cannot find symbol
System.out.println(arraylist.add());
^
symbol: method add()
location: variable arraylist of type Arraylist
1 error

If we try to  get rid of the error by doing some changes like creating my own Arraylist class as below.

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
Arraylist arraylist=new Arraylist();
System.out.println(arraylist.add(10));
System.out.println(arraylist);
}
}

class Arraylist{
public String add(int a){
return “Mehtod message……..”+a;
}
}

o/p:
D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
Mehtod message……..10
Arraylist@15db9742

But it is not the functionality what i intended to do  so I move one step forward and I am giving here the fully qualified name i.e java.util.Arraylist<E>.

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
java.util.ArrayList<Integer> arraylist=new java.util.ArrayList<Integer>();
System.out.println(arraylist.add(10));
System.out.println(arraylist);
}
}

class Arraylist{
public String add(int a){
return “Mehtod message……..”+a;
}
}

o/p:
D:\OCJP\imports>java StaticVsNormalVsNo_Imports
true
[10]

Now functionality is working as expected ,but what if i want’s to use 100 or 10 arraylists.In this case writing of java.util.ArrayList<Integer> arraylist=new java.util.ArrayList<Integer>(); 100 times or 10 times doesn’t make sense.So here java people import statement to rescue.

import java.util.ArrayList;

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
ArrayList<Integer> arraylist=new .ArrayList<Integer>();
System.out.println(arraylist.add(10));
System.out.println(arraylist);
}
}

o/p:

true [10]

What import java.util.ArrayList saying is whenever compiler sees the word ArrayList in the class it will use the java.util.ArrayList i.e in the JAVA API document there is a package called util and in that package there is class called ArrayList.

Here A package may contains many number of classes if i want to use one or more classes in a perticular package ,We are having an option wildcard character(*).If compiler sees the * symobol in import declaration it will search for all the classes in the entire package.

import java.util.*;

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
ArrayList<Integer> arraylist=new ArrayList<Integer>();
System.out.println(arraylist.add(10));
System.out.println(arraylist);

//Key shouldn’t be null in treemap
//If we put two keys similar it will ovverride
//multiple Null values are allowed
TreeMap<String,String> treeMap=new TreeMap<String,String>();
treeMap.put(“null”,null);
treeMap.put(“null1”,null);
treeMap.put(“null”,”nuller”);
treeMap.put(“null2″,null);
System.out.println(treeMap);

//one key can be null
//If we put two keys similar it will ovverride
HashMap<String,String> hashMap=new HashMap<String,String>();
hashMap.put(null,null);
hashMap.put(null,”null1”);
hashMap.put(“null1”,null);
hashMap.put(“null2″,null);
hashMap.put(null,”nuller”);
System.out.println(hashMap);

//No nulls as keys as well as values too
Hashtable<String,String> hashTable=new Hashtable<String,String>();
hashTable.put(“null”,”null-1″);
hashTable.put(“null1″,”null”);
hashTable.put(“null1″,”nuller”);
System.out.println(hashTable);

}
}

o/p:

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
true
[10]
{null=nuller, null1=null, null2=null}
{null=nuller, null1=null, null2=null}
{null=null-1, null1=nuller}

static imports in JAVA:

If we want to access the static members and methods of a class with out using the classname evrytime i.e Classname.XXXXX etc.Here is the example

System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.toHexString(123));

instead of putting class name every time we will go for static import.

import java.util.*;
import java.util.concurrent.*;

import static java.lang.System.out;
import static java.lang.Integer.*;
//static import won’t work
public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
out.println(MAX_VALUE);
out.println(MIN_VALUE);
out.println(toHexString(123));

o/p:

D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
2147483647
-2147483648
7b

but it is having dis advantage like

  • readability
  • both Long and Integer having MAX_VALUE etc similar properties in this case if we put wild card import(*)  it leads us to Compile Time Error.

Creating object(s) for class,interface,Abstract class,final class and enum in JAVA.

In java every communication among the classes merely done by the methods with the help of objects.The below link shows the various advantages with object in java.

Advantages with Object:

  • Define the structure and behavior of a class.
  • Independence-i.e One object values doesn’t affects the other object values.
  • Modularity- Once it got created ,We can move the object over methods or any where in the program.

Bundling code into individual software objects provides a number of benefits, including:

  1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
  2. Information-hiding: By interacting only with an object’s methods, the details of its internal implementation remain hidden from the outside world.
  3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
  4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

WHY WE NEED OBJECT IN JAVA….? 

Creating a object for Class:

  • There are numerous ways to create an object for a particular class in java.But here i am showing only the most generalized way i.e using new keyword.

class Demo{
public String string;
//Definfing the structure of class
public Demo(String str){
this.string=str;
System.out.println(“In construcor”+string);
}
//Here we are changing the behabiour of class through method
public String getName(){
return “Brad Pitt”;
}
}
public class Demo_Object{
public static void main(String[] args)throws Exception{
//creating the object with new() operator
Demo demoObject=new Demo(” Mr..”);
String str=demoObject.getName();
System.out.println(str);
}
}

o/p:
D:\OCJP>javac Demo_Object.java

D:\OCJP>java Demo_Object
In construcor Mr..
Brad Pitt

 

Creating Object for an interface:

As all of us knew that interface is a kind of class but the only difference we see is abstraction i.e interface is 100% abstract.Directly we can’t create object for interface.Why so,Here are nice explanations

https://www.quora.com/Why-cant-we-create-an-object-to-interface-in-Java

http://softwareengineering.stackexchange.com/questions/263301/i-want-to-understand-clearly-why-cant-we-instantiate-an-object-of-an-abstract-c

But through Anonymous classes we can create the objects.Example programs are below.

interface TestInterface{
String toString();
}

public class Object_Creation3{
public static void main(String[] args)throws Exception{
System.out.println(new TestInterface(){
public String toString(){
return “HAAAAAAAAAAAhhhaaaaaaa”+this.getClass();
}
});
}
}

o/p:

D:\OCJP>javac Object_Creation3.java

D:\OCJP>java Object_Creation3
HAAAAAAAAAAAhhhaaaaaaaclass Object_Creation3$1

 

With that syntax, you create an anonymous class, which is perfectly legal.

Internally, anonymous classes are compiled to a class of their own, called EnclosingClass$n where the enclosing class’ name precedes the $ sign. and n increases for each additional anonymous class. This means that the following class is being created:

 

Object Creation for Abstract class:

We can’t create for object for an Abstract class because if we do also the implementation must happen i.e through extends otherwise it will left remains as an empty template.

Because it’s abstract and an object is concrete. An abstract class is sort of like a template, or an empty/partially empty structure, you have to extend it and build on it before you can use it.

Take for example an “Animal” abstract class. There’s no such thing as a “pure” animal – there are specific types of animals. So you can instantiate Dog and Cat and Turtle, but you shouldn’t be able to instantiate plain Animal – that’s just a basic template. And there’s certain functionality that all animals share, such as “makeSound()", but that can’t be defined on the base Animal level. So if you could create an Animal object and you would call makeSound(), how would the object know which sound to make?

 

abstract class AbstractClassSample{
public String name;
//public AbstractClassSample(String name){
//this.name=name;
//}
public abstract void getName();
public String getCompany(){
return “OpenText”;
}
}

public class Abstract_ObjectCreation{
public static void main(String[] args)throws Exception{
AbstractClassSample abstractClassSample=new AbstractClassSample(“Sundar pichai”);
System.out.println(abstractClassSample.getCompany());
}
}

o/p:

D:\OCJP>javac Abstract_ObjectCreation.java
Abstract_ObjectCreation.java:14: error: AbstractClassSample is abstract; cannot
be instantiated
AbstractClassSample abstractClassSample=new AbstractClassSample(“Sundar picha
i”);
^
1 error

But we can get benefit with inheritance in the case of Abstract class by extending the abstract class to sub class and creating object for sub class as below.

abstract class AbstractClassSample{
public String designation=”Software Engineer”;
public AbstractClassSample(String d){
this.designation=d;
}
public abstract String getName();
public String getCompany(){
return “OpenText”;
}
}

class Abstract_Inheritence extends AbstractClassSample{
public int employeeId;
public Abstract_Inheritence(int no,String d){
super(d);
this.employeeId=no;
}
public String getName(){
return “Madhu”;
}
//public String getCompany(){
// return “PegaSystems”;
// }
}

public class Test_Inhiritence{
public static void main(String[] args)throws Exception{
Abstract_Inheritence abstract_Inheritence=new Abstract_Inheritence(123,”Associate”);
String s1=abstract_Inheritence.getName();
String s2=abstract_Inheritence.getCompany();
System.out.println(s1);
System.out.println(s2);
}
}

o/p:

D:\OCJP>javac Test_Inhiritence.java

D:\OCJP>java Test_Inhiritence
Madhu
OpenText

 

 

Object Creation for final class:

We can create object for a final class as normal i.e first use case.

final class Final_Demo{
public Final_Demo(String a){
System.out.println(“In Constructor”+a);
}
}

public class FinalClassObject{
public static void main(String[] args)throws Exception{
Final_Demo finalDemo=new Final_Demo(“Mr.Ramanjan”);
}
}

o/p:
D:\OCJP>javac FinalClassObject.java

D:\OCJP>java FinalClassObject
In ConstructorMr.Ramanjan

But final class cannot be extended .It will throgh the error as below.

final class Final_Demo{
public Final_Demo(String a){
System.out.println(“In Constructor”+a);
}
}

public class FinalClassObject extends Final_Demo{
public static void main(String[] args)throws Exception{
Final_Demo finalDemo=new Final_Demo(“Mr.Ramanjan”);
System.out.println(“errorr……”);
}
}

o/p:

D:\OCJP>javac FinalClassObject.java
FinalClassObject.java:7: error: cannot inherit from final Final_Demo
public class FinalClassObject extends Final_Demo{
^
FinalClassObject.java:7: error: constructor Final_Demo in class Final_Demo canno
t be applied to given types;
public class FinalClassObject extends Final_Demo{
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
2 errors

Creating Object for enum:

Enums cannot be intialized as they only a private constructor.

public enum Sample{
   READ,WRITE
}   


//Will get convetred the above code into below internally.


class Sample extends Enum {
    public static final Sample READ = new Sample("READ", 0);
    public static final Sample WRITE = new Sample("WRITE", 1);

    private Sample(String s, int i)
    {
        super(s, i);
    }

    // More methods, e.g. getter
}