question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
I am using Liquibase for generating a MySQL and a HSQLDB databases. In several tables I have a column called 'last_modified' which is the TIMESTAMP of the last update on that particular record. <changeSet author="bob" id="7"> <createTable tableName="myTable"> <column autoIncrement="true" name="id" type="I...
Or you could try this, as you have already have modifySql tag added: <column defaultValue="CURRENT_TIMESTAMP" name="timestamp" type="TIMESTAMP"> <constraints nullable="false"/> </column> <modifySql dbms="mysql"> <regExpReplace replace="'CURRENT_TIMESTAMP'" with="CURRENT_TIMEST...
Liquibase
19,230,489
14
Starting yesterday (Sunday) morning my production app fails to start, with no code changes from my side. It's running Springboot 2.3.4, Liquibase-core 3.8.0 and is hosted on Amazon linux2. Funny thing is there are no exceptions locally, only when deployed. Here is the relevant stack trace: Caused by: liquibase.exceptio...
I had the same problem. On the startup of the amazon linux 2, there is a security patch that is installed. The package causing the problem is log4j-cve-2021-44228-hotpatch.noarch (you can check that in /var/log/yum.log) A temporary solution is to uninstall the patch and install another java version. yum remove log4j-cv...
Liquibase
70,421,613
14
I have an entity with a group of fields in primary key. Like this : @Entity @Table(name = "pv_object") @NamedQuery(name = "PreviousObject.findAll", query = "SELECT p FROM PreviousObject p") public class PreviousObject implements Serializable { @EmbeddedId private FieldsDTO fieldsdto; // } FieldsDTO clas...
In <addPrimaryKey you can configure columnNames by all your columns that compose your primary key <changeSet author="liquibase-docs" id="addPrimaryKey-example"> <addPrimaryKey columnNames="id, name" constraintName="pk_person" schemaName="public" tableName="person" tablespace...
Liquibase
54,440,479
14
I have a Spring Boot 1.4.0 based Project that uses Liquibase. Is it possible to execute a Method AFTER liquibase finished? Something like Bean Post Processor? What i want to do is adding some data to my database when the application is started in development mode. In developement mode the application uses an in-memory ...
Spring Boot auto-configures a SpringLiquibase bean named liquibase. Any bean that depends on this bean will be created after Liquibase has finished. For example, you could use @PostConstruct to populate the database: @Bean @DependsOn("liquibase") public YourBean yourBean() { return new YourBean(); } static class Y...
Liquibase
38,825,670
14
I have fresh mysql instance and want to be able to create a plenty of databases and populate it with liquibase. While I have scripts (changesets) which works fine on manually created databases I want to be able to create databases with liquibase as well. When I try to connect without specifing database in URL I've got ...
Very first need to add database name in URL like jdbc:mysql://localhost:3306/database_name. you can also create a fresh database using this URL jdbc:mysql://localhost:3306/database_name?createDatabaseIfNotExist=true createDatabaseIfNotExist this keyword create a fresh new database in your system. If the database do...
Liquibase
34,283,630
14
This is what I have --preconditions onFail:CONTINUE --preconditions not tableExists tableName:QRTZ_CALENDARS schemaName:dbo CREATE TABLE dbo.QRTZ_CALENDARS ( SCHED_NAME VARCHAR (120) NOT NULL , CALENDAR_NAME VARCHAR (200) NOT NULL , CALENDAR IMAGE NOT NULL ) GO Background. I'm using liquibase to setup a h2 datab...
Add a pre-Condition to your changeset for example: <preConditions onFail="MARK_RAN"> <not> <tableExists tableName="Table_name"/> </not> </preConditions> <createTable tableName="Table_name" > <column name="column1" type="NUMBER(20,0)"/> </createTable>
Liquibase
48,015,336
14
I am looking to drop a table in MySQL using Liquibase only if the table exists. I am not able to figure out how to check if a table exists in Liquibase.
You should use <changeSet author="liquibase-docs" id="dropTable-example"> <preConditions onFail="MARK_RAN"><tableExists schemaName="schemaName" tableName="tableName"/></preConditions> <dropTable cascadeConstraints="true" catalogName="cat" schemaName="public" tableName="perso...
Liquibase
44,083,766
14
I'm having a SQL syntax error when my Spring Boot application tries to start. It cannot instantiate the SpringLiquibase bean, because the outputed SQL of a changeset is leading to a syntax error. I need to check the SQL generated from Liquibase in order to find what's wrong. How can I do that?
You can try liquibase updateSQL command http://www.liquibase.org/documentation/command_line.html http://www.liquibase.org/documentation/update.html
Liquibase
28,636,472
14
I am working with the new Spring Boot 2.1.0 version. In Spring Boot 2.1.0, Liquibase was updated from 3.5.5 to 3.6.2. I've noticed several things in my change sets are no long working. -- test_table.sql CREATE TABLE test_table ( id SERIAL PRIMARY KEY, --Works fine as TEXT or VARCHAR with Liquibase...
They broke TEXT data type. Try to use VARCHAR May be it could be interesting too https://liquibase.jira.com/browse/CORE-865 You can find all availible types here https://github.com/liquibase/liquibase/tree/master/liquibase-core/src/main/java/liquibase/datatype/core I think that NVARCHAR(MAX) should works for you Also ...
Liquibase
53,405,317
13
How to tell Liquibase to map BLOB datatype to BYTEA on PostgreSQL? It seems that Hibernate people has taken over and adapted the tool to their needs: https://liquibase.jira.com/browse/CORE-1863 , however, EclipseLink don't support oid's and the bug seems to be still open: https://bugs.eclipse.org/bugs/show_bug.cgi?id=3...
You have two options. If you only need this for Postgres and don't plan to support other DBMS, simply use bytea as the column type. Any data type that is not listed as one of the "generic" types in the description of the column tag will be passed "as-is" to the database, e.g. <createTable tableName="foo"> <column na...
Liquibase
42,388,886
13
I`m trying to include changeset.yaml file into changelog.yaml for Liquidbase. file changelog.yaml databaseChangeLog: - include: file: migrations/changeset.yaml changeset.yaml changeset: id: 1 author: vlad Getting this when executing update Unexpected error running Liquibase: Could not find databaseChangeL...
changeset.yaml must contain databaseChangeLog So in my case i should have had this: changeset.yaml databaseChangeLog: - changeSet: id: 1 author: vlad Documentation wasn`t really helpful. Found answer here in github
Liquibase
33,563,763
13
In my current project, there's a DB team that checks all the scripts before applying them to production. We are using Liquibase to apply changesets to development, but for production, we need to be able to generate a *.sql file with all the statements. According to the documentation of liquibase-maven-plugin, updateSQL...
UpdateSQL does not actually update the database, it just outputs SQL. The reason it needs the database connection information and makes an actual connection because it needs to select from the databasechangelog table to determine which changeSets have been ran and which have not.
Liquibase
22,941,876
13
In Liquibase I would like to insert values if the values are not already set. With a normal insert I suspect that the inserted value will overwrite the previous value if the value is already there. I want it to ony insert if it does not exist. Can this be done? Right now I am using the insert as seen below: <insert tab...
The proper way to do this is to use preConditions. There's an <sqlCheck> preCondition. sqlCheck Executes an SQL string and checks the returned value. The SQL must return a single row with a single value. To check numbers of rows, use the “count” SQL function. To check for ranges of values, perform the check in ...
Liquibase
61,845,118
12
How do I create a composite index using liquibase? This is what I have so far: <createIndex indexName="idx_value" tableName="test"> <column name="value"/> </createIndex> I have the following in mind, but I just need to confirm. <createIndex indexName="idx_value" tableName=...
I'd be amazed if: <createIndex indexName="idx_value" tableName="test"> <column name="value" type="varchar(255)"/> <column name="othercolumn" type="varchar(255)"/> </createIndex> didn't work...
Liquibase
24,254,201
12
Looking at the docs for liquibase and add-foreign-key-constraint there is a property called deferrable. But the docs don't really mention what that property does. Anyone know?
DEFERRABLE NOT DEFERRABLE This controls whether the constraint can be deferred. A constraint that is not deferrable will be checked immediately after every command. Checking of constraints that are deferrable may be postponed until the end of the transaction (using the SET CONSTRAINTS command). NOT DEFERRABLE is the de...
Liquibase
11,405,034
12
Running liquibase --url=jdbc:oracle:thin:@localhost:1521/XE -- driver=oracle.jdbc.OracleDriver --changeLogFile=db.changelog-next.xml -- username=owner --password=xxxx --logLevel=info clearCheckSums clears ALL checksums from the database. Is there a way to clear only the checksums for changesets in db.changelog...
I don't think there is another command or a parameter to clearCheckSums that does this. But you could do this manually. All that clearCheckSums does is nullifying the MD5SUM column of the databasechangelog table. So something like: update databasechangelog set md5sum=null where filename like '%db.changelog-next.xml...
Liquibase
30,472,289
12
According to the liquibase website, there is an intellij IDEA plugin available in the plugin store, but I cannot seem to find it. Is the plugin discontinued? Is there some alternative for liquibase integrations?
Yes, the Liquibase Intellij plugin has been discontinued. I'll update the website to remove the reference.
Liquibase
33,285,267
12
I want to add a unique constraint to my table during it's creation. I thought something like this would work but it seems to just do nothing. <createTable tableName="MY_TABLE"> <column name="MY_TABLE_ID" type="SMALLINT" autoIncrement="true"> <constraints primaryKey="true" nullable="false"/> </column> <co...
Try adding unique="true" to <constraints>. <createTable tableName="MY_TABLE"> <column name="MY_TABLE_ID" type="SMALLINT" autoIncrement="true"> <constraints primaryKey="true" nullable="false"/> </column> <column name="TABLE_FIELD" type="SMALLINT"> <constraints nullable="false...
Liquibase
52,950,169
12
Following this documentation: To automatically run Liquibase database migrations on startup, add the org.liquibase:liquibase-core to your classpath. The master change log is by default read from db/changelog/db.changelog-master.yaml but can be set using liquibase.change-log. In addition to YAML, Liquibase also support...
I believe you are missing <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> in your dependencies
Liquibase
41,960,588
12
I am using Postgresql for my db and created all the entities using the JHipster entity wizard. When I try to make any changes like adding/removing fields, relations to an existing entity I am getting a check sum error and Liquibase is not starting. Also, I haven't made any changes on the DB manually. Any help is apprec...
Executed the following query in Postgres DB which resolved the issue: UPDATE databasechangelog SET md5sum = null
Liquibase
41,019,034
12
I want to insert usernames to the database based on a system property. The system property value can be users="user1;user2;user3" This process must be repeatable, meaning that every time the applications is deployed, the migration/changeset must check the system property, and if it has changed and the users are not a...
A standard attribute available to all changesets is the runAlways attribute, which should do what you want. There is also a runOnChange attribute available. Documentation on the attributes available is here: http://www.liquibase.org/documentation/changeset.html
Liquibase
35,775,597
12
I am implementing a changeset in Liquibase that needs a few different preconditions to be valid before it attempts to run. Scenario #1: If table A,B,C exists, mark as ran Scenario #2: If table X,Y,Z doesn't exist, halt execution of changeset In other words, I need two <preConditions> tags with different onFail clauses....
It is not allowed currently. There can be just one block. Would it work to break it up into two separate changeSets?
Liquibase
18,866,793
12
We use liquibase to keep track of our database changes.. First changeSet contains those lines: <column name="SHORT_ID" type="INTEGER"> <constraints unique="true" /> </column> Basically it means that SHORT_ID column has unique constraint but the name of this constraint can be whatever and usually is different each t...
Liquibase provides an implementation for dropping a not null constraint without knowing the constraint name. It may not have existed when this question was asked (I realise it's quite old). dropNotNullConstraint <dropNotNullConstraint catalogName="cat" columnDataType="int" columnName="id" ...
Liquibase
3,618,234
12
We use liquibase to manage one of our MySQL databases' updates, rollbacks, etc. One small curiosity I've come across is the process of setting values to null in the course of updates or rollbacks. Example: <rollback> <update tableName="boats"> <column name="engine" value="null" /> ...
Just omit the value attribute on <column>: <rollback> <update tableName="boats"> <column name="engine" type="varchar(255)"/> </update> </rollback> Reference: Update
Liquibase
50,110,456
11
I'm using spring-boot with the liquibase-maven-plugin to generate database changes according to my classes, but the "mvn compile liquibase: diff" command always generates removals and inclusions of indexes and foreign keys even though the database is updated and has no change in the classes (and therefore should have n...
First of all, I think you are missing the liquibase-hibernate4 maven plugin. From the project Readme.md: This extension lets you use your Hibernate configuration as a comparison database for diff, diffChangeLog and generateChangeLog in Liquibase. Which actually means that you can use it to compare the real database ...
Liquibase
46,019,203
11
I have spring boot application which use 2 databases. I defined 2 configurations providing specified datasources. I want to have that datasources managed separately by liquibase. I defined 2 separated changelog files. The problem is that I can't define 2 separate beans for liquibase. Here are my config classes: ... p...
there are two options: you define a bean named liquibase to let spring-boot integrated process to update your schema on you first DS. You have to handle the second one by hand you disable liquibase automatic update at startup with enabled: false and define your way DS and liquibase beans to update your two database...
Liquibase
43,346,062
11
I'm looking into Liquibase as a potential solution to deploy my web application using pre-existing database servers (of different types). This application should access the database with a user that can only manipulate data, I would like to use a different user as schema owner. Since my application uses Spring I though...
Using Liquibase with Spring Boot (at least 2.0+), there is now the possibility to configure a separate Liquibase db user in your application.yml: spring: datasource: driver-class-name: org.mariadb.jdbc.Driver url: jdbc:mariadb://... username: <app_user> password: ${DB_PASSWORD} liquibase: defaul...
Liquibase
26,774,525
11
For our application we use liquibase. We have a need to run DB migrations both from command line (manually on production) AND automatically as the application starts up (test environment etc). The problem is that Liquibase considers the whole filename as a portion of a changeSet's identity, therefore it tries to reappl...
Based on this, the approach is as follows: Always use the logicalFilePath attribute on both the databaseChangeLog element and every changeSet element. Example: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <databaseChangeLog logicalFilePath="does-not-matter" xmlns="http://www.liquibase.org/xml/ns/dbchangelog"...
Liquibase
19,959,755
11
I'm getting my hands on the Liquibase tool and I'd like to mimic working with an existing database. From the command line, I managed to generate the changelog. I was wondering whether it's possible to generate insert statements for data insides the tables?
Yes. Use the --diffTypes="data" parameter output CSV files that are referenced from the generated changelog and will populate your database.
Liquibase
3,290,983
11
I'm using SpringLiquibase for liquibase configuration, below configuration works fine with single changelog file (sql formatted) @Configuration @Slf4j public class LiquibaseConfiguration { @Inject private DataSource dataSource; @Bean public SpringLiquibase liquibase() { log.info("################## Enteri...
One of the possible solution: you can create the main changelog, which will includes other changelogs as much as you wish. And in the SpringLiquibase object you will set only one main liquibase changelog. For example, assume you have 2 changelog files: one-changelog.xml and two-changelog.xml and you need to run the bot...
Liquibase
56,292,517
11
I am using Spring-Liquibase to perform any migration that is needed on the staging database. The applicationContext.xml looks like <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" ...
The problem is often because part of the unique identifier for each changeSet is the path to the changelog file. It looks like it currently sees it as "liquibase/2014/1-1.xml". If you run select * from databasechangelog where id='05192014.1525' what is the path already in the database?
Liquibase
24,168,223
11
I am getting the following liquibase error when I run my Spring Boot application: Specifying files by absolute path was removed in Liquibase 4.0. Please use a relative path or add '/' to the classpath parameter. Here is the class path in application.yaml: liquibase: change-log: classpath:db/changelog/db-changelog...
I got this issue when putting the changelog files outside the resources folder, but if I include them under resources/db/changelog, then it would work fine with setting the bellow config. spring.liquibase.change-log=classpath:/db/changelog/changelog-master.xml Tested under 4.6.2
Liquibase
68,874,846
11
I am looking for an example on how to use the <whereparams></whereparams> which belongs to <update></update>, but I couldn't find anything (even in the official documentation). any help is much appreciated.thanks.
An example usage is <update tableName="updateTest"> <column name="varcharColumn" value="new column 1 value"/> <column name="dateCol" valueDate="2008-01-01"/> <column name="intCol" valueNumeric="11"/> <where>id=:value</where> <whereParams> <param valueNumeric="134" />...
Liquibase
22,941,373
11
I've read about how you can generate changelog.xml from an existing schema. That's fine, but I have existing systems that I don't want to touch, except to bring in new changes. I also have completely new systems which require all changes be applied. So, I want to get liquibase to only perform migrations from changeset ...
I would recommend a slightly different approach, as commented in this Liquibase forum thread generate a changelog from your existing schema. The liquibase CLI can do that for you. I usually take the resulting XML and smooth it out a bit (group related changes into single changelogs, do vendor-specific cleanups and so...
Liquibase
6,912,125
11
I currently have the following in my application.properties: liquibase.change-log=classpath:/db/changelog/db.changelog-master.xml The actual path to the file is src/main/resources/db/changelog/db.changelog-master.xml. The changelog is found by Liquibase and everything is working as I would expect. I've moved the change...
I'm an idiot. My local ~/.m2 repository had an old version of the jar without the Liquibase changelog. A mvn clean install fixed the issue.
Liquibase
30,353,472
10
I'm using SpringLiquibase to apply my liquibase update automatically during the application startup. In general this works fine, but when I set hibernate.hbm2ddl.auto to "validate" then hibernate starts to complain about the database scheme before liquibase seems to have the chance to apply the updates. My configuratio...
Thanks to M. Deinum I was able to solve this by using @Bean @DependsOn("liquibase") public LocalContainerEntityManagerFactoryBean entityManagerFactory() { [...] } The @DependsOn makes sure that liquibase is run before Hibernates schema validation.
Liquibase
27,677,656
10
I am using liquibase 3.5.3 to run liquibase update command on MySql 5.5. I have below changeSet to create a table which has a column as Created_Time that should have a default value as CURRENT_TIMESTAMP. <changeSet author="authorName" id="AutoGeneratedId"> <createTable tableName="aTable"> <column autoIncrem...
Add type as 'TIMESTAMP' as following <column defaultValueComputed="CURRENT_TIMESTAMP" name="Created_Time" type="TIMESTAMP"/>
Liquibase
48,793,666
10
I am trying to export data from an Oracle (ojdbc7) database using liquibase. My property file has below options: driver: oracle.jdbc.driver.OracleDriver url: jdbc:oracle:thin:@localhost:1521:XE username: user password: user outputChangeLogFile:src/main/resources/output.xml defaultSchemaName: USERS In STS I used below...
I would suggest try to export data via CLI liquibase version. Download it here, unpack, put ojdbc7.jar into liquibase folder: liquibase --driver=oracle.jdbc.OracleDriver \ --classpath=\path\to\classes:ojdbc7.jar \ --changeLogFile=db.changelog.xml \ --url="jdbc:oracle:thin:@localhost:1521:XE" \ -...
Liquibase
41,627,301
10
Tried to find an answer to this question, but couldn't. So, for example I have this table: TABLE: col1 | col2 123 0 124 1 and I want to change col2 value to 1 and this is how I'm trying to do it: <changeSet author="myName" id="7799"> <sql> UPDATE TABLENAME; SET COL1='1' WHERE col1='...
You can use the following liquibase syntax to update: <changeSet author="myname" id="7799"> <update catalogName="dbname" schemaName="public" tableName="TABLENAME"> <column name="COL1" value='1' type="varchar(50)"/> <where>col1='123'</where> </update> </changeSet> For the...
Liquibase
16,655,504
10
I have a bunch of sql scripts that create / drop sequences, users and other objects. I'm running these scripts through liquibase, but they fail because oracle complains when I try to drop a non existing sequence, or create an existing user. Is there an oracle way to prevent errors from happening? Something of the sort...
Liquibase has a failOnError attribute you can set to false on changeSets that include a call that could fail. <changeSet failOnError="false"> <createSequence sequenceName="new_sequence"/> </changeSet> This allows you to have simple create user, create sequence, drop user, and drop sequence changeSets and if the s...
Liquibase
1,625,567
10
Here is the structure, one of the maven dependency jar project, which one contains liquibase change logs in classpath as following: chorke─init─change-1.0.00.GA.jar! └─ META-INF/ └─ migrations/ ├─ db.changelog-master.xml ├─ config/ │ ├─ db.changelog-config.xml │ ├─ db.changelog-...
The structure mentioned for chorke─init─change-1.0.00.GA.jar contains liquibase change logs in classpath is good enough and spring-boot application.properties also configured exactly. But there were some silly mistake in liquibase-maven-plugin configuration, It should be corrected as following: <configuration> <pro...
Liquibase
46,810,712
10
Using gradle-liquibase plugin in our project with all dependencies resolved. I have the following liquibase task as suggested by Gradle liquibase plugin: liquibase { activities { main { changeLogFile 'src/main/resources/db/dbchangelog-master.xml' url 'jdbc:mysql://localhost:3306/test' use...
Just add a classpath parameter where your src directory is liquibase { activities { main { changeLogFile 'src/main/resources/db/dbchangelog-master.xml' url 'jdbc:mysql://localhost:3306/test' username 'XXX' password 'XXX' classpath "$rootDir" } } runList = 'main' }
Liquibase
27,187,979
10
I am new to R2DBC (https://r2dbc.io/). I would like to know whether r2dbc's ecosystem has a database migration tool/framework. It seems Liquibase & Flyway depend on JDBC. Is there a plan for allowing those frameworks to support a r2dbc driver? Any input or feedback welcome.
Steve's answer is correct hat R2DBC is primarily about interaction with the actual data. I'd like to add a different perspective. It's true that a reactive API does not provide any improvement during migrations. In fact, looking closely, migrations are part of the startup process which is typically synchronous, at lea...
Liquibase
57,183,169
10
I'm currently using Liquibase in a small project of mine, which works pretty fine. But right now i'm facing a problem. My ChangeLog works as expected in my testenv but fails on my productiv one. This happens because my prod-tables contain a few rows of data. I know there is an UPDATE-Command in liquibase, but im not s...
It may look like <changeSet ...> <update tableName="TABLE_A"> <column name="x" valueComputed="(select b.x from TABLE_B b where b.id=id)"/> </update> </changeset>
Liquibase
33,820,620
10
As described here (https://github.com/liquibase/liquibase-hibernate/issues/74) I'm having an issue getting the liquibase-hibernate extension to work properly. I think I have everything setup, but it seems like I keep running into weird problems. I feel like I'm missing something simple, but I think I've followed all th...
I got it working by adding these jars to my classpath. This is super confusing and not well documented. The process I went through was: Download the source for the correct plugin project found here (https://github.com/liquibase/liquibase-hibernate/releases) in my case it was liquibase-hibernate4-3.5. Run mvn dependenc...
Liquibase
28,029,556
10
I have been trying for quite some time to figure out a solution for my problem, to no avail. Anyway, i have a bunch of integration tests (in a nonstandard directory testRegression parallel to the standard test directory). These integration tests use an h2 in memory database. In production as well as for testing i am us...
I had the same issue, and it seems to have been caused by case sensitive checking of the database table name. That is, the table was created as 'DATABASECHANGELOG', but Liquibase was checking for the existence of 'databasechangelog'. The fix (at least for an H2 database) is to specify case insensitive identifiers in th...
Liquibase
63,036,299
10
My package structure is looks like: In /db.changelog/db.changelod-master.xml i include /db.changelog/v1/db.changelog-1.0.xml where i also include all changelogs from /db.changelog/v1/changeset package. In my application, I have two profiles: dev and prod, and I need to divide the structure of packages according to "B...
Solution1: You need to define 'liquibase.contexts' property into your yaml file. Something like below. spring: profiles: dev datasource: url: jdbc:postgresql://localhost:5432/dev username: postgres password: password driver-class-name: org.postgresql.Driver liquibase: contexts: dev After adding ...
Liquibase
52,645,232
10
I'm having a hard time setting up LiquiBase in my Spring Boot project. I tried looking through the docs and finding some guides - but they seem contradict each other. I wish to use LiquiBase via Gradle and I want it to generate the changelogs from Hibernate and end up with a SQL script I can run on the server to update...
Turns out I needed to add some undocumented magic sauce. diff.dependsOn compileJava diffChangeLog.dependsOn compileJava generateChangelog.dependsOn compileJava dependencies { // as before liquibaseRuntime sourceSets.main.output // replaces liquibaseRuntime files('src/main') }
Liquibase
52,517,215
10
I have a spring boot application and I want to add liquibase configuration change log for it. I have created a LiquibaseConfig class for configuring liquibase: @Configuration public class LiquibaseConfiguration { @Value("${com.foo.bar.liquibase.changelog}") private String changelog; @Autowired MysqlDa...
Here's a simple step to integrate liquibase in spring boot STEP 1 Add liquibase dependency Gradle runtime "org.liquibase:liquibase-core" Maven <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <scope>runtime</scope> </dependency> STEP 2 Add liquibase changelog file pat...
Liquibase
41,491,234
10
I have a Spring boot, spring data jpa project with a parent and three children modules. One of my modules is responsible for my JPA entities. I need generate one xml changelog with liquibase from this entities. In my liquibase.properties i have the code: changeLogFile=src/main/resources/db/changelog/db.changelog-master...
i solved this problem. The solution is one dependency it's missing in my pom.xml file. Pom.xml <!-- Liquibase --> <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.liquibase<...
Liquibase
36,549,359
10
A Spring Boot Java application using Liquibase to manage the database schema changes is started with a parameter (e.g. dev, int) specifying the environment it runs in. There are corresponding properties files (e.g. dev.properties, int.properties) which define properties for the corresponding environment. So in dev.prop...
As you are using Spring Boot, you can use its application.properties file to define change log parameters. Any property with a name that begins with spring.liquibase.parameters. can be referenced in a changelog. For example, the property spring.liquibase.parameters.url.info can be referenced as ${url.info} in your chan...
Liquibase
34,326,981
10
I configured Jenkins in Spinnaker as follows and setup the Spinnaker pipeline. jenkins: # If you are integrating Jenkins, set its location here using the baseUrl # field and provide the username/password credentials. # You must also enable the "igor" service listed separately. # # If you have multi...
Finally, this post helped me to do away with the crumb problem, but still securing Jenkins from a CSRF attack. Solution for no-valid crumb included in the request issue Basically, we need to first request for a crumb with authentication and then issue a POST API calls with a crumb as a header along with authentication ...
Spinnaker
44,711,696
108
I've heard both used to describe the idea of deploying an update on new machines while keeping old machines active, ready to rollback if an issue occurs. I've also heard it used to describe sharing load between updated services and old service, again for the purpose of a rollbacks —sometimes terminating inactive older ...
Blue-green deployment Classic deployment technique described in the Continuous Delivery book by Jez Humble and David Farley: The idea is to have two identical versions of your production environment, which we’ll call blue and green... Users of the system are routed to the green environment, which is the currently desi...
Spinnaker
45,259,589
90
I was following this documentation to setup Spinnaker on Kubernetes. I ran the scripts as they specified. Then the replication controllers and services are started. But some of PODs are not started root@nveeru~# kubectl get pods --namespace=spinnaker NAME READY STATUS RESTARTS ...
use halyard to install spinnaker. it is the recommended approach for deploying spinnaker in kubernetes clsuter
Spinnaker
39,570,765
20
K8 Version: Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T18:44:27Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"} Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1....
Running the following command resolved my issues: kubeadm init --pod-network-cidr=10.244.0.0/16 For flannel as cni the api server needs to have the argument --pod-network-cidr=... to be set to the overlay.
Spinnaker
44,305,615
16
I would like to know what each strategy means and how they work behind the scenes (i.e., Highlander, Red/Black, Rolling Push). It would be very useful to have this information on the official website. Thanks
There is useful information out there that can help you with your question, I'll do my best to summarize it below. Type and Strategies of Deployments Introduction "There are a variety of techniques to deploy new applications to production, so choosing the right strategy is an important decision, weighing the options i...
Spinnaker
36,072,412
12
I have a values.yaml file in which I have given spring_datasource_hikari_maximum_pool_size: "10" In deployment yaml I have used this value as - name: SPRING_DATASOURCE_HIKARI_MAXIMUM-POOL-SIZE value: {{ .Values.spring_datasource_hikari_maximum_pool_size }} However, when used inside the deployment.yaml file it fai...
I was able to resolve this by using double quotes on the value itself in deployment.yaml file - name: SPRING_DATASOURCE_HIKARI_MAXIMUM-POOL-SIZE value: "{{ .Values.spring_datasource_hikari_maximum_pool_size }}" Since this was a production instance I could not check with @David Maze and Vit's solution. Edit: Tried wi...
Spinnaker
68,013,476
11
I've heard these words related to concurrent programming, but what's the difference between lock, mutex and semaphore?
A lock allows only one thread to enter the part that's locked and the lock is not shared with any other processes. A mutex is the same as a lock but it can be system wide (shared by multiple processes). A semaphore does the same as a mutex but allows x number of threads to enter, this can be used for example to limit t...
Semaphore
2,332,765
666
What are the major differences between a Monitor and a Semaphore?
A Monitor is an object designed to be accessed from multiple threads. The member functions or methods of a monitor object will enforce mutual exclusion, so only one thread may be performing any action on the object at a given time. If one thread is currently executing a member function of the object then any other thre...
Semaphore
7,335,950
278
When to use a semaphore and when to use a conditional variable?
Locks are used for mutual exclusion. When you want to ensure that a piece of code is atomic, put a lock around it. You could theoretically use a binary semaphore to do this, but that's a special case. Semaphores and condition variables build on top of the mutual exclusion provide by locks and are used for providing s...
Semaphore
3,513,045
160
Here is the code I have but I don't understand what SemaphoreSlim is doing. async Task WorkerMainAsync() { SemaphoreSlim ss = new SemaphoreSlim(10); List<Task> trackedTasks = new List<Task>(); while (DoMore()) { await ss.WaitAsync(); trackedTasks.Add(Task.Run(() => { ...
In the kindergarden around the corner they use a SemaphoreSlim to control how many kids can play in the PE room. They painted on the floor, outside of the room, 5 pairs of footprints. As the kids arrive, they leave their shoes on a free pair of footprints and enter the room. Once they are done playing they come out, co...
Semaphore
20,056,727
159
Their public interfaces appear similar. The documentation states that the SemaphoreSlim is a lightweight alternative and doesn't use Windows Kernel semaphores. This resource states that the SemaphoreSlim is much faster. In what situations does the SemaphoreSlim make more sense over the Semaphore and vice versa?
One difference is that SemaphoreSlim does not permit named semaphores, which can be system-wide. This would mean that a SemaphoreSlim could not be used for cross-process synchronization. The MSDN documentation also indicates that SemSlim should be used when "wait times are expected to be very short". That would usually...
Semaphore
4,154,480
143
Is there a Mutex object in java or a way to create one? I am asking because a Semaphore object initialized with 1 permit does not help me. Think of this case: try { semaphore.acquire(); //do stuff semaphore.release(); } catch (Exception e) { semaphore.release(); } if an exception happens at the first acqui...
Any object in Java can be used as a lock using a synchronized block. This will also automatically take care of releasing the lock when an exception occurs. Object someObject = ...; synchronized (someObject) { ... } You can read more about this here: Intrinsic Locks and Synchronization
Semaphore
5,291,041
134
What is mutex and semaphore in Java ? What is the main difference ?
Unfortunately everyone has missed the most important difference between the semaphore and the mutex; the concept of "ownership". Semaphores have no notion of ownership, this means that any thread can release a semaphore (this can lead to many problems in itself but can help with "death detection"). Whereas a mutex doe...
Semaphore
771,347
119
Is there any advantage of using java.util.concurrent.CountdownLatch instead of java.util.concurrent.Semaphore? As far as I can tell the following fragments are almost equivalent: 1. Semaphore final Semaphore sem = new Semaphore(0); for (int i = 0; i < num_threads; ++ i) { Thread t = new Thread() { public void r...
CountDownLatch is frequently used for the exact opposite of your example. Generally, you would have many threads blocking on await() that would all start simultaneously when the countown reached zero. final CountDownLatch countdown = new CountDownLatch(1); for (int i = 0; i < 10; ++ i) { Thread racecar = new Thread...
Semaphore
184,147
114
I would like to run a bunch of async tasks, with a limit on how many tasks may be pending completion at any given time. Say you have 1000 URLs, and you only want to have 50 requests open at a time; but as soon as one request completes, you open up a connection to the next URL in the list. That way, there are always exa...
As suggested, use TPL Dataflow. A TransformBlock<TInput, TOutput> may be what you're looking for. You define a MaxDegreeOfParallelism to limit how many strings can be transformed (i.e., how many urls can be downloaded) in parallel. You then post urls to the block, and when you're done you tell the block you're done add...
Semaphore
22,492,383
69
I am working on some code which uses the pthread and semaphore libraries. The sem_init function works fine on my Ubuntu machine, but on OS X the sem_init function has absolutely no effect. Is there something wrong with the library or is there a different way of doing it? This is the code I am using to test. sem_t sem1;...
Unnamed semaphores are not supported, you need to use named semaphores. To use named semaphores instead of unnamed semaphores, use sem_open instead of sem_init, and use sem_close and sem_unlink instead of sem_destroy.
Semaphore
1,413,785
66
I read that mutex is a semaphore with value 1 (binary semaphore) used to enforce mutual exclusion. I read this link Semaphore vs. Monitors - what's the difference? which says that monitor helps in achieving mutual exclusion. Can someone tell me the difference between mutex and monitor as both help achieve the same thin...
Since you haven't specified which OS or language/library you are talking about, let me answer in a generic way. Conceptually they are the same. But usually they are implemented slightly differently Monitor Usually, the implementation of monitors is faster/light-weight, since it is designed for multi-threaded synchroniz...
Semaphore
38,159,668
54
I would assume that I am aware of how to work with DispatchGroup, for understanding the issue, I've tried: class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() performUsingGroup() } func performUsingGroup() { let dq1 = DispatchQueue.global(qos:...
Conceptually, both of DispatchGroup and Semaphore serve the same purpose (unless I misunderstand something). The above is not exactly true. You can use a semaphore to do the same thing as a dispatch group but it is much more general. Dispatch groups are used when you have a load of things you want to do that can all ...
Semaphore
49,923,810
53
I have multiple apps compiled with g++, running in Ubuntu. I'm using named semaphores to co-ordinate between different processes. All works fine except in the following situation: If one of the processes calls sem_wait() or sem_timedwait() to decrement the semaphore and then crashes or is killed -9 before it gets a c...
Turns out there isn't a way to reliably recover the semaphore. Sure, anyone can post_sem() to the named semaphore to get the count to increase past zero again, but how to tell when such a recovery is needed? The API provided is too limited and doesn't indicate in any way when this has happened. Beware of the ipc tool...
Semaphore
2,053,679
51
What are the pros / cons of using pthread_cond_wait or using a semaphore ? I am waiting for a state change like this : pthread_mutex_lock(&cam->video_lock); while(cam->status == WAIT_DISPLAY) { pthread_cond_wait(&cam->video_cond, &cam->video_lock); } pthread_mutex_unlock(&cam->video_lock); Using a properly initial...
A semaphore is suited cleanly to a producer-consumer model, although it has other uses. Your program logic is responsible for ensuring that the right number of posts are made for the number of waits. If you post a semaphore and nobody is waiting on it yet, then when they do wait they continue immediately. If your probl...
Semaphore
70,773
49
According to the documentation: "a SemaphoreSlim doesn't use a Windows kernel semaphore". Are there any special resources used by the SemaphoreSlim which make it important to call Dispose when the SemaphoreSlim will no longer be used?
If you access the AvailableWaitHandle property, then Yes, you must call Dispose() to cleanup unmanaged resources. If you do not access AvailableWaitHandle, then No, calling Dispose() won't do anything important. SemaphoreSlim will create a ManualResetEvent on demand if you access the AvailableWaitHandle. This may be u...
Semaphore
32,033,416
45
Throughout the resources I've read about multithreading, mutex is more often used and discussed compared to a semaphore. My question is when do you use a semaphore over a mutex? I don't see semaphores in Boost thread. Does that mean semaphores no longer used much these days? As far as I've understand, semaphores allow ...
The typical use case for a mutex (allowing only one thread access to a resource at any time) is far more common than the typical uses if a semaphore. But a semaphore is actually the more general concept: A mutex is (almost) a special case of a semaphore. Typical applications would be: You don't want to create more than...
Semaphore
2,350,544
44
I'm looking for mutex/semaphore/concurrency mechanism in shell script. Consider following situation: Unless "a" user does not close the shared file, "b" user should not able to open/update it. I'm just wondering how to implement mutex, semaphore, critical sections, etc. in shell scripting. Which is the easiest way ...
The BashFAQ noted by shellter has some good examples. The basic idea, which I'm moving here so the page is self-contained, is to use an operation that both tests and sets at the same time: mkdir mkdir will fail if the directory exists and will make it if it does not. It's an atomic operation and you can use it like so ...
Semaphore
6,870,221
44
This is an interview question. Is it possible to use mutex in multiprocessing case on Linux/UNIX ? My idea: No, different processes have separate memory space. mutex is only used for multithreading. semaphore is used for multiprocessing to do synchronization. right ? Any comments are welcome. thanks
Mutual exclusion locks (mutexes) prevent multiple threads from simultaneously executing critical sections of code that access shared data (that is, mutexes are used to serialize the execution of threads). All mutexes must be global. A successful call for a mutex lock by way of mutex_lock() will caus...
Semaphore
9,389,730
42
Trying to use a semaphore to control asynchronous requests to control the requests to my target host but I am getting the following error which I have assume means that my asycio.sleep() is not actually sleeping. How can I fix this? I want to add a delay to my requests for each URL targeted. Error: RuntimeWarning: coro...
asyncio.sleep(delay) Change it to: await asyncio.sleep(delay) asyncio.sleep is a coroutine and should be awaited.
Semaphore
54,088,263
41
I have to synchronize N client processes with one server. These processes are forked by a main function in which I declared 3 semaphores. I decided to use POSIX semaphores but I don't know how to share them between these processes. I thought that shared memory should work correctly, but I have some questions: How can...
It's easy to share named POSIX semaphores Choose a name for your semaphore #define SNAME "/mysem" Use sem_open with O_CREAT in the process that creates them sem_t *sem = sem_open(SNAME, O_CREAT, 0644, 3); /* Initial value is 3. */ Open semaphores in the other processes sem_t *sem = sem_open(SEM_NAME, 0); /* Open a p...
Semaphore
8,359,322
37
I've been trying to understand Reentrant locks and Semaphores ( the nesting of Reentrant locks vs release/unlock mechanism ). It seems that having a Semaphore requires you to write a more thoroughly tested application because the release() method does not check if the thread releasing the permit is actually holding it....
there is no real reason ever to have a binary semaphore as everything that a binary semaphore can do can also be done by a ReentrantLock If all you need is reentrant mutual exclusion, then yes, there is no reason to use a binary semaphore over a ReentrantLock. If for any reason you need non-ownership-release seman...
Semaphore
17,683,575
37
I have read the docs for SemaphoreSlim SemaphoreSlim MSDN which indicates that the SemaphoreSlim will limit a section of code to be run by only 1 thread at a time if you configure it as: SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1); However, it doesn't indicate if it stops the same thread from accessing that...
From the documentation: The SemaphoreSlim class doesn’t enforce thread or task identity on calls to the Wait, WaitAsync, and Release methods In other words, the class doesn't look to see which thread is calling it. It's just a simple counter. The same thread can acquire the semaphore multiple times, and that will be ...
Semaphore
40,985,233
35
What are the trade-offs between using a System V and a Posix semaphore?
From O'Reilly: One marked difference between the System V and POSIX semaphore implementations is that in System V you can control how much the semaphore count can be increased or decreased; whereas in POSIX, the semaphore count is increased and decreased by 1. POSIX semaphores do not allow manipulation of s...
Semaphore
368,322
33
How do i tell if one instance of my program is running? I thought I could do this with a data file but it would just be messy :( I want to do this as I only want 1 instance to ever be open at one point.
As Jon first suggested, you can try creating a mutex. Call CreateMutex. If you get a non-null handle back, then call GetLastError. It will tell you whether you were the one who created the mutex or whether the mutex was already open before (Error_Already_Exists). Note that it is not necessary to acquire ownership of th...
Semaphore
459,554
32
I am doing experiments with IPC, especially with Mutex, Semaphore and Spin Lock. What I learnt is Mutex is used for Asynchronous Locking (with sleeping (as per theories I read on NET)) Mechanism, Semaphore are Synchronous Locking (with Signaling and Sleeping) Mechanism, and Spin Locks are Synchronous but Non-sleeping M...
First, remember the goal of these 'synchronizing objects' : These objects were designed to provide an efficient and coherent use of 'shared data' between more than 1 thread among 1 process or from different processes. These objects can be 'acquired' or 'released'. That is it!!! End of story!!! Now, if it helps to you, ...
Semaphore
23,511,058
31
Perhaps it's too late at night, but I can't think of a nice way to do this. I've started a bunch of asynchronous downloads, and I want to wait until they all complete before the program terminates. This leads me to believe I should increment something when a download starts, and decrement it when it finishes. But then ...
Check out the CountdownLatch class in this magazine article. Update: now covered by the framework since version 4.0, CountdownEvent class.
Semaphore
1,965,578
30
Please tell what is difference between a Semaphore initialized with 1 and Vs. intialized zero, as below: public static Semaphore semOne = new Semaphore(1); and public static Semaphore semZero = new Semaphore(0);
The argument to the Semaphore instance is the number of "permits" that are available. It can be any integer, not just 0 or 1. For semZero all acquire() calls will block and tryAcquire() calls will return false, until you do a release() For semOne the first acquire() calls will succeed and the rest will block until the...
Semaphore
25,563,640
30
What is the difference between Counting and binary semaphore. What I have seen somewhere is that both can control N number of processes which have requested for a resource. Both have taken and Free states. Is there any restriction on how many Resources a Binary semaphore and Counting semaphore can protect? Both allow...
Actually, both types are used to synchronize access to a shared resource, whether the entity which is trying to access is a process or even a thread. The difference is as follows: Binary semaphores are binary, they can have two values only; one to represent that a process/thread is in the critical section(code that acc...
Semaphore
10,898,022
29
When I run this code in Python 3.7: import asyncio sem = asyncio.Semaphore(2) async def work(): async with sem: print('working') await asyncio.sleep(1) async def main(): await asyncio.gather(work(), work(), work()) asyncio.run(main()) It fails with RuntimeError: $ python3 demo.py working wo...
Python 3.10+: This error message should not occur anymore, see answer from @mmdanziger: (...) the implementation of Semaphore has been changed and no longer grabs the current loop on init Python 3.9 and older: It's because Semaphore constructor sets its _loop attribute – in asyncio/locks.py: class Semaphore(_ContextM...
Semaphore
55,918,048
28
I know that threading.Lock() is equal to threading.Semaphore(1). Is also threading.Lock() equal to threading.BoundedSemaphore(1) ? And newly I saw threading.BoundedSemaphore(), what is the difference between them? For example in the following code snippet (applying limitation on threads): import threading sem = thread...
A Semaphore can be released more times than it's acquired, and that will raise its counter above the starting value. A BoundedSemaphore can't be raised above the starting value. from threading import Semaphore, BoundedSemaphore # Usually, you create a Semaphore that will allow a certain number of threads # into a sect...
Semaphore
48,971,121
28
I want to fork multiple processes and then use a semaphore on them. Here is what I tried: sem_init(&sem, 1, 1); /* semaphore*, pshared, value */ . . . if(pid != 0){ /* parent process */ wait(NULL); /* wait all child processes */ printf("\nParent: All children have exited.\n"); . . /* cleanup sema...
The problem you are facing is the misunderstanding of sem_init() function. When you read the manual page you will see this: The pshared argument indicates whether this semaphore is to be shared between the threads of a process, or between processes. If you are done reading up to this point, you will think that the ...
Semaphore
16,400,820
27
I'm currently training for an OS exam with previous iterations and I came across this: Implement a "N Process Barrier", that is, making sure that each process out of a group of them waits, at some point in its respective execution, for the other processes to reach their given point. You have the following ops availabl...
This is well presented in The Little Book of Semaphores. n = the number of threads count = 0 mutex = Semaphore(1) barrier = Semaphore(0) mutex.wait() count = count + 1 mutex.signal() if count == n: barrier.signal() # unblock ONE thread barrier.wait() barrier.signal() # once we are unblocked, it's our duty to unbloc...
Semaphore
6,331,301
27
I am trying to understand the usefulness of fairness property in Semaphore class. Specifically to quote the Javadoc mentions that: Generally, semaphores used to control resource access should be initialized as fair, to ensure that no thread is starved out from accessing a resource. When using semaphores for other kin...
Java's built-in concurrency constructs (synchronized, wait(), notify(),...) do not specify which thread should be freed when a lock is released. It is up to the JVM implementation to decide which algorithm to use. Fairness gives you more control: when the lock is released, the thread with the longest wait time is given...
Semaphore
17,825,508
26
I want to check the state of a Semaphore to see if it is signalled or not (so if t is signalled, I can release it). How can I do this? EDIT1: I have two threads, one would wait on semaphore and the other should release a Semaphore. The problem is that the second thread may call Release() several times when the first t...
You can check to see if a Semaphore is signaled by calling WaitOne and passing a timeout value of 0 as a parameter. This will cause WaitOne to return immediately with a true or false value indicating whether the semaphore was signaled. This, of course, could change the state of the semaphore which makes it cumbersome t...
Semaphore
7,330,834
25
Nonbinary ones.. I have never encountered a problem that required me to use a semaphore instead of mutex. So is this mostly theoretical construct, or real sw like Office, Firefox have places where they use it? If so what are the common use patterns for semaphores?
Non-binary semaphores are used in resource allocation. A semaphore might hold the count of the number of a particular resource. If you have a pool of connections, such as a web browser might use, then an individual thread might reserve a member of the pool by waiting on the semaphore to get a connection, uses the conne...
Semaphore
21,736,741
25
I've got the following code and the semaphore wouldn't lock it as expected. (I'm aware of apc_inc. This is not what I'm looking for.) $semkey = sem_get(123); sem_acquire($semkey); $count = apc_fetch('count111'); if(!$count) $count = 0; $count++; apc_store('count111', $count); sem_release($semkey); followed by ab -n ...
The problem was, apparently, with the APC itself, not with the semaphore. Updating to PHP 5.4.8-1~dotdeb.0 has solved the problem for both nginx and built-in server test runs.
Semaphore
12,407,767
23
How to interrupt all Cypress tests on the first test failure? We are using semaphore to launch complete e2e tests with Cypress for each PR. But it takes too much time. I'd like to interrupt all tests on the first test failure. Getting the complete errors is each developer's business when they develop. I just want to ...
EDIT: It seems like this feature was introduced, but it requires paid version of Cypress (Business Plan). More about it: Docs, comment in the thread Original answer: This has been a long-requested feature in Cypress for some reason still has not been introduced. There are some workarounds proposed by the community, ho...
Semaphore
61,661,932
23
Does anybody know why semaphore operations are called P and V? Every time I read a chapter on semaphores it says something like the following: In order for the thread to obtain a resource it executes a P operation. And in order for the thread to release a resource it executes a V operation. What does P and V stand for?...
Dijkstra, one of the inventors of semaphores, used P and V. The letters come from the Dutch words Probeer (try) and Verhoog (increment). See also: https://cs.nyu.edu/~yap/classes/os/resources/origin_of_PV.html
Semaphore
29,606,162
23
Short version Is it possible to share a semaphore (or any other synchronization lock) between user space and kernel space? Named POSIX semaphores have kernel persistence, that's why I was wondering if it is possible to also create, and/or access them from kernel context. Searching the internet didn't help much due to t...
Well, you were in the right direction, but not quite - Linux named POSIX semaphore are based on FUTex, which stands for Fast User-space Mutex. As the name implies, while their implementation is assisted by the kernel, a big chunk of it is done by user code. Sharing such a semaphore between kernel and user space would r...
Semaphore
17,391,276
23
I need to stop a thread until another thread sets a boolean value and I don't want to share between them an event. What I currently have is the following code using a Sleep (and that's the code I want to change): while (!_engine.IsReadyToStop()) { System.Threading.Thread.Sleep(Properties.Settings.Default.IntervalFo...
SpinWait.SpinUntil is the right answer, regardless where you're gonna place this code. SpinUntil offers "a nice mix of spinning, yielding, and sleeping in between invocations".
Semaphore
12,412,167
23
What do I need and how can I use threads in C on Windows Vista? Could you please give me a simple code example?
Here is the MSDN sample on how to use CreateThread() on Windows. The basic idea is you call CreateThread() and pass it a pointer to your thread function, which is what will be run on the target thread once it is created. The simplest code to do it is: #include <windows.h> DWORD WINAPI ThreadFunc(void* data) { // D...
Semaphore
1,981,459
22
I'm trying to find out what is the difference between the SemaphoreSlim use of Wait and WaitAsync, used in this kind of context: private SemaphoreSlim semaphore = new SemaphoreSlim(1); public async Task<string> Get() { // What's the difference between using Wait and WaitAsync here? this.semaphore.Wait(); // await...
If you have async method - you want to avoid any blocking calls if possible. SemaphoreSlim.Wait() is a blocking call. So what will happen if you use Wait() and semaphore is not available at the moment? It will block the caller, which is very unexpected thing for async methods: // this will _block_ despite calling async...
Semaphore
44,305,825
19
I have a slice of integers, which are manipulated concurrently: ints := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} I'm using a buffered channel as semaphore in order to have an upper bound of concurrently running go routines: sem := make(chan struct{}, 2) for _, i := range ints { // acquire semaphore sem <- struct{}{} ...
You can't use a semaphore (channel in this case) in that manner. There's no guarantee it won't be empty any point while you are processing values and dispatching more goroutines. That's not a concern in this case specifically since you're dispatching work synchronously, but because there's no race-free way to check a c...
Semaphore
39,776,481
19